Best Way To Implement Multi Language Frontends In Laravel 5 (Multiple Domains)

- 1 answer

I'm developing a laravel (5.0) application and have come across a new requirement to implement support for another language. One good thing that I did was implement Localisation from the beginning so now I have two folders under /resources/lang/ 'en' for english and 'es' for spanish.

I use the trans helper function to display the string in my view like so:

   {!! trans('front.views.index.empty_list') !!}

In my /config/app.config file, I have defined the locale as the default 'en'. For this application, I now use two domains (.com - for english and .es for Spanish). The .com domain is the one the application currently uses, the .es domain is setup as an alias.

So ultimately my question would be, how can I implement some kind of check in Laravel which defines which domain is currently being used - Something I have looked into is Group Routes but I'm unsure how I would use this. I would like the .com domain to display English (which it currently does) and when using .es It should switch to Spanish.



I think a nice way to do this is using a middleware. First create one:

php artisan make:middleware SetLanguage

Enable it in Http\Kernel.php:

protected $routeMiddleware = [
    'language' => \App\Http\Middleware\SetLanguage::class,

Finally, implement the handle() method in SetLanguage class:

public function handle($request, Closure $next)
    $domain = parse_url($request->url(), PHP_URL_HOST);

    switch($domain) {
        case '':
            $language = 'es';

            $language = 'en';

    View::share('language', $language); // Could be useful in views?

    return $next($request);

Enable this middleware for any controller and the locale will be set automatically. I usually have a config file somewhere in configs/ folder with all languages supported and corresponding domain names.