Laravel; 如何使setLocale永久化?

rea*_*ebo 4 php laravel laravel-5

我有回家的路线

Route::get('/', 'HomeController@index')->name('home');
Run Code Online (Sandbox Code Playgroud)

以及改变语言的特定途径

Route::get('/setLocale/{locale}', 'HomeController@setLocale')->name('setLocale');
Run Code Online (Sandbox Code Playgroud)

HomeController->setLocale($locale)我检查是否$locale是有效的语言环境,然后只需

\App::setLocale($locale);
Run Code Online (Sandbox Code Playgroud)

然后重定向到家。

在这里,HomeController->index()我使用

$locale = \App::getLocale();
Run Code Online (Sandbox Code Playgroud)

问题在于,在用户更改了语言环境之后,该应用会设置新的语言环境并重定向,但检测到的语言环境仍然是默认语言环境,而不是用户设置的新语言环境。

如何/在何处/何时可以持久更改应用程序区域设置?

我以为Laravel在使用时设置了语言环境cookie或其他内容,然后在使用时setLocale重新读取了它,getLocale但现在我认为Laravel并不是这种方式。

我再次问:如何设置应用程序语言环境,以便在页面更改后保留该语言环境?

小智 9

我通过使用中间件来做到这一点。这是我的代码:

语言中间件:

public function handle($request, Closure $next)
{
    if(session()->has('locale'))
        app()->setLocale(session('locale'));
    app()->setLocale(config('app.locale'));

    return $next($request);
}
Run Code Online (Sandbox Code Playgroud)

记得注册您的中间件:)

用户可以使用简单的GET-Route来更改语言:

Route::get('/lang/{key}', function ($key) {
    session()->put('locale', $key);
    return redirect()->back();
});
Run Code Online (Sandbox Code Playgroud)

希望对您有帮助:)