9
votes

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
Use session/cache to store locale \App:setLocale('ufo-language') sets locale only for request life. Anyway use routes for it and do not save anything for search engine sake.Kyslik
Customer asked me to avoid locale slug. He preferred the url translationrealtebo
Does your customer know all the ramifications? It seems stupid but if there is a translation for site, google will never know, since it seems that g-bot does not store cookies. CheersKyslik
We exports sitemap. google will known every page. Also, every controller use the url segmemts to identify the language. Very bad idea, but customer want itrealtebo

2 Answers

18
votes

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

Apparently, there are some changes in Laravel 7.0!

If you are using the code above, please change from a BeforeMiddleware to a AfterMiddleware! (see https://laravel.com/docs/7.x/middleware)

If you don't do this, the value of session('locale') will always be null!

3
votes

setlocale only works for the current request. If you want the value to be remembered, you will have to set a cookie manualy.

I recommend using a middleware to do this.