Laravel localization using session not applying globally (locale changes in session but app()->getLocale() stays unchanged)

17 hours ago 1
ARTICLE AD BOX

I am trying to implement localization (English/Japanese) in a Laravel 12 project using session-based language switching.

I have a route to switch language:

Route::get('/lang/{locale}', function ($locale) { if (!in_array($locale, ['en', 'ja'])) { abort(400); } session()->put('locale', $locale); return redirect()->back(); })->name('lang.switch');

I created a middleware:

namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; class SetLocale { public function handle($request, Closure $next) { $locale = session('locale', 'en'); App::setLocale($locale); return $next($request); } }

And registered it in Kernel.php inside the web middleware group:

protected $middlewareGroups = [ 'web' => [ \Illuminate\Cookie\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \App\Http\Middleware\SetLocale::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ];

In my Blade view (dashboard.blade.php), I display:

SESSION: {{ session('locale') }} <br> APP: {{ app()->getLocale() }} <h1>{{ __('messages.dashboard') }}</h1> <h2>{{ __('messages.system_overview') }}</h2>

Translation files:

resources/lang/en/messages.php

return [ 'dashboard' => 'Dashboard', 'system_overview' => 'System Overview', ];

resources/lang/ja/messages.php

return [ 'dashboard' => 'ダッシュボード', 'system_overview' => 'システム概要', ];

Problem

session('locale') changes correctly (en / ja)

Navigation menu translates correctly

BUT on the dashboard:

app()->getLocale() remains en

Translations do not update


What I tried

Clearing cache:

php artisan optimize:clear php artisan view:clear

Verified middleware is registered

Verified translation files are correct

Removed duplicate keys in language files

Middleware is being executed correctly


Question

Why would session('locale') update correctly, but app()->getLocale() not reflect it inside Blade views?

Is there something specific in Laravel 12 regarding middleware execution order or localization handling that I might be missing?


Any help would be greatly appreciated

Read Entire Article