Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

extjac's avatar

Language setLocale - not working.

Trying to make the app multi lang. This client has Laravel 7.x so i need to upgrade on a later date. For now, i want to update the menu to be multi lang. I create a json file for en.json fr.json and es.json /resources/lang

en.json
{
    "Login": "Login",
}
es.json
{
    "Login": "Ingresar",
}

And the route looks like this

Route::get('/lang/{locale}', function ($locale) {

    if (!in_array($locale, ['en', 'fr','es'])) {
        abort(400);
    }

    App::setLocale($locale);

    return redirect()->back();

});

and the view looks like this...

<h3 class="text-center mb-3">{{ trans('Login') }}   </h3>
<h3 class="text-center mb-3">{{ __('Login') }}   </h3>

Problem is that it does not work. It will not change the language. However, if change the config/app.php to

    'locale' => 'es',

it works......

anyone please?

0 likes
2 replies
Rebwar's avatar
Rebwar
Best Answer
Level 32

To ensure the consistent application of the selected locale, it is necessary to store the locale in the session. so update your route:

Route::get('/lang/{locale}', function ($locale) {

    if (!in_array($locale, ['en', 'fr','es'])) {
        abort(400);
    }

    App::setLocale($locale);
	session()->put('locale', $locale);

    return redirect()->back();

});

create a middleware that examines the locale stored within the session,

artisan make:middleware Localization
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
use Symfony\Component\HttpFoundation\Response;

class Localization
{
    public function handle(Request $request, Closure $next): Response
    {
		if (Session::has('locale')) {
            App::setLocale(Session::get('locale'));
        }
        return $next($request);
    }
}

add the newly created middleware into your kernel.php file, within the middlewareGroups array, to enable its functionality throughout your application's request lifecycle.

protected $middlewareGroups = [
        'web' => [
            ...
			\App\Http\Middleware\Localization::class,
        ]
];

now, your application will utilize the selected locale for all of its pages

1 like
extjac's avatar

@Rebwar thank you! just same a small change to your code...

    public function handle($request, Closure $next)
    {

        if( Session::has('locale') ) {

            App::setLocale( Session::get('locale') );
        
        } else {
        
            App::setLocale( config('app.fallback_locale') );
        
        }

        return $next($request);

    }

Please or to participate in this conversation.