Set Locale in Laravel with prefix translated routes

TLDR; In this article, we will discuss how we can use route prefixes to set locale in a Laravel app.

Posted by Mohamed Irfan on 2019-Nov-16

Localization

An important step of developing a web application or creating web content is making sure that it can be localized, in other words adapting a website into a different linguistic and cultural context.

Localization in Laravel

One way achieve Localization would be to have a prefix in the route for the locale and then set the language according to the prefix in the route. So when user hit those routes the locale gets selected and all the content changes to serve with prefix included.

Why a Middleware ?

We can actually define the routes manually in web.php in Laravel . For example

Route::get('/en/blog', function () {
    App::setLocale('en');
    return view('blog');
});

But this can be fine when we do not have much routes. But if we consider the real life scenario, it has much more context than this, its obvious that there is going to be many routes like this.so handling them individually is not efficient. So we can introduce a middleware to do the job of, detecting the prefix and setting up the locale, and then apply it to a group of routes which is also a handy feature in Laravel.

Let's Begin !

  • First Create a Middleware to handle the requests
php artisan make:middleware SetLocale

Write the logic of handling the prefixes in the routes in handle() function created in the new middleware SetLocale


  • Register the new middleware in app/Http/Kernel.php
protected $routeMiddleware = [
    .....
    'locale' => \App\Http\Middleware\SetLocale::class,
];
  • Now group the routes with the middleware
Route::group(['prefix' => '/{locale}', 'middleware' => 'locale'], function ($locale) {

    Route::get('/contact-us', function () {
        return view('contact-us');
    });
    Route::get('/faqs', function () {
        return view('faqs');
    });
    Route::get('/blog', function () {
        return view('blog');
    });
});

That's all we need to do for the Prefix translated routes in Laravel. Whenever we have to add a route with a locale prefix, add it inside this route group, and do the translation related tasks in the blade file. Once again Laravel has different ways of fetching translated words to blade files. The most widely used is the @lang() annotation For example,

@lang('filename.key')

Check the official documentation for more information about localization.

Conclusion

Laravel provides lot of features for localization. Using Prefix translated routes is the most preferred way of handling localization and this post basically explains an efficient way of handling prefix translation in Laravel.