首页 > 解决方案 > 使用 Axios 切换 Laravel 语言环境

问题描述

我想通过 axios 调用更改我的语言环境:

changeLanguage(code) {
                return axios
                    .put(`/api/lang/` + code)
                    .then(response => {
                        console.log(response.data);
                    })
                    .catch(err => {
                        return "Error switching language";
                        console.log(err.response);
                    });
            },

我的 API 路线:

Route::group(['middleware' => ['sessions']], function () {
    Route::put('lang/{language}', 'LanguageController@switchLang');
});

我的会话中间件:

'sessions' => [
            \Illuminate\Session\Middleware\StartSession::class,
        ]

我的语言控制器:

public function switchLang(Request $request, $lang)
{
        session(['applocale' => $lang]);
        app()->setLocale($lang);
} 

我的索引控制器:

public function index()
{
        \Debugbar::info("Index getLocale is: " . app()->getLocale());
        \Debugbar::info("Index Session locale is: " . session('applocale'));
}

问题是 LanguageController 无法设置可以从 IndexController 读取的会话变量。看起来他们不共享相同的会话变量。每次我刷新页面时,它都会显示旧语言。

使用 Axios 更改当前语言环境的正确方法是什么?

标签: laravelsessionlocalizationlocaleaxios

解决方案


推荐阅读