Laravel;如何使setLocale永久化? [英] Laravel; how make setLocale permanent?

查看:93
本文介绍了Laravel;如何使setLocale永久化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有回家的路线

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

以及更改语言的特定途径

And a specific route to change language

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

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

In HomeController->setLocale($locale) I check if $locale is a valid locale, then simply do

\App::setLocale($locale);

然后重定向到首页.

在这里,我在HomeController->index()中使用验证语言环境

Here, in HomeController->index() I verify locale using

$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?

我认为Laravel在使用setLocale时会设置区域设置cookie或其他内容,而在使用getLocale时会重新读取它,但是现在我认为Laravel的工作方式并非如此.

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.

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

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:

LanguageMiddleware:

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

    return $next($request);
}

记住要注册您的中间件:)

remember to register your middleware :)

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

The users are able to change the language, with a simple GET-Route:

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

希望对您有所帮助:)

这篇关于Laravel;如何使setLocale永久化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆