简体   繁体   English

拉拉维尔; 如何使 setLocale 永久化?

[英]Laravel; how make setLocale permanent?

I've my home route我有我的回家路线

Route::get('/', 'HomeController@index')->name('home');

And a specific route to change language以及改变语言的特定途径

Route::get('/setLocale/{locale}', 'HomeController@setLocale')->name('setLocale');

In HomeController->setLocale($locale) I check if $locale is a valid locale, then simply doHomeController->setLocale($locale)我检查$locale是否是有效的语言环境,然后简单地做

\App::setLocale($locale);

Then redirect to home.然后重定向到家。

Here, in HomeController->index() I verify locale using在这里,在HomeController->index()我使用

$locale = \App::getLocale();

The problem is that after user CHANGES the locale, the app set the new locale, redirect, but the locale detected is still the DEFAULT locale, not the new one setup by the user.问题是在用户更改区域设置后,应用程序设置了新的区域设置、重定向,但检测到的区域设置仍然是默认区域设置,而不是用户设置的新区域设置。

How / where / when can I make persistent the change to app locale?如何/在何处/何时可以持久更改应用程序区域设置?

I thinked Laravel was setting a locale cookies or something when using setLocale and re-reading it when using getLocale but now I think it's not this the way Laravel works.我认为 Laravel 在使用setLocale时设置了区域设置 cookie 或其他东西,并在使用getLocale时重新读取它,但现在我认为这不是 Laravel 的工作方式。

I ask, again: how can I set app locale so that is preserved after page change?我再次问:如何设置应用程序区域设置以便在页面更改后保留?

I did that by using a middleware.我通过使用中间件做到了这一点。 Here's my code:这是我的代码:

LanguageMiddleware:语言中间件:

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

    return $next($request);
}

remember to register your middleware :)记得注册你的中间件:)

The users are able to change the language, with a simple GET-Route:用户可以使用简单的 GET-Route 更改语言:

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

Hopefully that helps you :)希望对你有帮助:)

Apparently, there are some changes in Laravel 7.0!显然,Laravel 7.0 有一些变化!

If you are using the code above, please change from a BeforeMiddleware to a AfterMiddleware!如果您正在使用上面的代码,请将 BeforeMiddleware 更改为 AfterMiddleware! (see https://laravel.com/docs/7.x/middleware ) (见https://laravel.com/docs/7.x/middleware

If you don't do this, the value of session('locale') will always be null!如果不这样做, session('locale')将始终为 null!

setlocale only works for the current request. setlocale仅适用于当前请求。 If you want the value to be remembered, you will have to set a cookie manualy.如果您希望记住该值,则必须手动设置 cookie。

I recommend using a middleware to do this.我建议使用中间件来做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM