duana1986 2017-06-09 10:57
浏览 171
已采纳

Laravel; 如何使setLocale永久化?

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 do

\App::setLocale($locale);

Then redirect to home.

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?

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?

  • 写回答

2条回答 默认 最新

  • douceng7070 2017-06-09 12:25
    关注

    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'));
        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:

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

    Hopefully that helps you :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?