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条)

报告相同问题?

悬赏问题

  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA