Route groups for localization in Laravel 5.1

1.4k views Asked by At

I have three languages on my site:

en, fr, de

I want all of the pages on the site to have the language in the url in the first segment, ie.

/page     ->set Locale as English
/de/page  ->set Locale as German
/fr/page  ->set Locale as French

Any idea how I can apply this to all routes? The language must be set based on the first URL segment, if its not 'de' or 'fr' then set the language as English. Thanks!

1

There are 1 answers

0
Anthony Vipond On

I've got it working now with a foreach loop.

<?php

// routes.php

Route::group(['middleware' => 'lang'], function () {

    $langPrefixes = array_merge(config('app.langs'), ['']);

    foreach ($langPrefixes as $lang)
    {
        Route::get($lang . '/', [
            'uses' => 'PropertyController@index'
        ]);

        Route::get($lang . '/stuff', [
            'uses' => 'PropertyController@stuff'
        ]);
    }

});

In config/app.php:

<?php

// config/app.php

'langs' => ['fr', 'de'], // new addition

And middleware:

<?php

// Middleware/SetLanguage.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Foundation\Application;

class SetLanguage
{
    protected $app;

    /**
     * Get access to the IoC container
     *
     * @param  Illuminate\Foundation\Application  $auth
     * @return void
     */
    public function __construct(Application $app)
    {
        $this->app = $app;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (in_array($request->segment(1), $this->app['config']['app.langs']) )
        {
            // override 'en' as the app locale
            $this->app['config']['app.locale'] = $request->segment(1);
        }

        return $next($request);
    }
}