Laravel - How to split and load additional JSON translation files on certain routes only?

profile
By Stefan Dreßler
March 31, 2023
Laravel - How to split and load additional JSON translation files on certain routes only?

If your Laravel application has to deal with a huge amount of translations, it can be very helpful to split them. This article shows how you can extend Laravel's powerful localization behaviors to organize or split additional JSON translation files and load them on specific routes only. This can be done by simply attaching a middleware to a route group.

This article is written for Laravel 10 applications.

Add JSON Translation Files

Create a folder in your application and add JSON files named like your locales. For example, it might look like this:

/**  
lang/
   vendor/
      landing/
          en.json
          de.json
**/

Add a function to a Service Provider of your choice

Currently, these translation files are not loaded. You can load them with the Laravel service provider function loadJsonTranslationsFrom(). For example, you can add it to your AppServiceProvider and call it from the middleware later.

// AppServiceProvider

/** Can be called from middleware */
public function loadLandingTranslations(): void
{
    $this->loadJsonTranslationsFrom(base_path() . '/lang/vendor/landing/');
}

Create a new middleware

Create a middleware and load your translations using your new service provider function.

class LoadLandingTranslations
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        // resolve the Service Provider 
        $provider = app()->resolveProvider(\App\Providers\AppServiceProvider::class);
        // call the function you created
        $provider->loadLandingTranslations();

        return $next($request);
    }
}

Register the middleware

Register the middleware in your kernel.php file.

protected $routeMiddleware = [
    ...
    'landing.translations' => \App\Http\Middleware\LoadLandingTranslations::class,
    ...
];

Add the middleware to a route group

Now you can attach this middleware to route groups. All wrapped routs will additionally load your additional JSON localization files. Your application routes are probably located in your /routes folder. Add the landing.translations middleware to a group.

Route::group(['middleware' => ['landing.translations']], function () {
    ...
    Route::get('/', 'Web\LandingController@home');
    ...
});

That's it. Your translation files will be loaded on routs with this middleware only.

If this article was helpful for you, or you have any suggestions or ideas, please send a message to our HelpSpace support team.

Image by Pro Church Media on Unsplash