Laravel; how make setLocale permanent?

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.


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!