phplaravellanguage-switching

Laravel Language Picker


Good day! I've been working on a Laravel project and I'm getting mad with the Language picker.

I have set on my app.php the locale which is the current language and an array named locales where I have all the languages (Spanish and English for now):

'locale' => 'es',

'locales' => [
    'en' => 'English',
    'es' => 'Castellano',
],

I've created a route that the user can access to change the language with the pattern /lang/es or /lang/en this way:

Route::get('/lang/{lang}', ['as'=>'lang.switch', 'uses'=>'HomeController@storeLang']);

And here the function storeLang:

    public function storeLang($lang){
        $cookie = null;

        if (array_key_exists($lang, Config::get('app.locales'))) {
            $cookie = Cookie::forever('locale', $lang);
            //App::setLocale($lang);
            var_dump(Config::get('app.locale'));
            exit();
        }

        if ($cookie) {
            return Redirect::back()->withCookie($cookie);
        }

        return back(); 
    }
}

My idea was to check if the $lang that we're passing is correct and if so, make a cookie which lasts forever with the language stored, but it's not making the locale to change, I suppose that I have to add something because this var_dump isn't returning me the language changed and I don't know how to make the cookie to change the locale.

On the other hand, as you can see I have the App::setLocale($lang) commented. I've used it and it seemed to work because in this case the var_dump was returning me the right language that I wanted to change to, but at the time to return to the page it was all with the old language again.

I'm getting mad with this, would be fabulous to get some help, thank you!


Solution

  • App::setLocale() is not persistent and sets locale only for current request.

    What you can do is you can set cookie (as you already done) and check it in a middleware. If there is any cookie then switch the application language.