Ad

Laravel 5 Multi Language Not Working

- 1 answer

I tried to localization my app, but seems like I'm missing something. I don't have any previous knowledge about this and therefore it's pretty hard to get started. Here is my routes.php

Route::get('/lang/{lang}', '[email protected]');

And here is my LangController.php

 public function index($lang)

{
    $langs =['en', 'de'];
    if(in_array($lang, $langs)){
        Session:set('lang', $lang);
        return Redirect::back();
    }
}

I set in middleware:(Lang.php)

 public function handle($request, Closure $next)

{

    if($lang = Session::get('lang')){
        \Lang::setLocale($lang);
    }

    return $next($request);
}

Enable it in Http\Kernel.php:

  protected $middleware = [

   \App\Http\Middleware\Lang::class,
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,

    ];

In my blade.php

 {{ Lang::get('home.hello')}}
   CURRENT: {{ Lang::getLocale() }} <br /> <br />
 <a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="{{ url('lang/de') }}">Germany</a> | <a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="{{ url('lang/en') }}">English</a>

Please help.I do not see what I missing... In field CURRENT when press Germany it shoul be 'de' and when press English it shoul be 'en' but when press Germany it still stay 'en'... (default is 'en' config/app.php -> 'locale' => 'en',)

Ad

Answer

Because you are using the session in your middleware, the values you need will not be available until the StartSession middleware sets up the session.

So you should add your middleware somewhere after that, like so:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class, // Init session
    \App\Http\Middleware\Lang::class, // Set locale
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
];

Aside from that you also have a small syntax error in your controller code. You forgot to add the second colon (:) for the scope resolution operator, when assigning the value to the session in your index controller method. So this:

Session:set('lang', $lang);

Should be this:

Session::set('lang', $lang);
Ad
source: stackoverflow.com
Ad