locale in laravel 5.4 returns to the pervious loca

2019-06-04 01:40发布

问题:

im learning the multi locale inn laravel 5.4 so i created two files first one in resources/lang/es/greeting.php

<?php

return [

    'hello' => 'hola',

];

and second in resources/lang/en/greeting.php

<?php

return [

    'hello' => 'hola',

];

and i created this route inside web.php

Route::get('/{locale}', function ($locale) {
    App::setLocale($locale);
    return view('index');

});

so when i request this link (localhost:8000/es) it works but when i refresh the page its returns to default locale which is en

and i want it to stay in the new locale so help me please

回答1:

If you want to set the locale permanently for that session, change the route code to:

Route::get('/{locale}', function ($locale) {
    App::setLocale($locale);
    Session::put('locale', $locale);
    return view('index');
});

Then add a middleware to check if session has locale, and if so set the locale like so:

public function handle($request, Closure $next) {
    if(Session::has('locale')) {
        app()->setLocale(Session::get('locale'));
    }
    return $next($request);
}