Are you seeing messages in the log on every single request from your middleware?
Issue with localization
I'm encountering an issue with persisting the user's selected locale across requests in my Laravel 11 application. I've implemented a language switcher that allows users to switch between English and French, and while the session seems to correctly store the selected locale, it does not persist across pages as expected.
Here's the relevant part of my implementation:
Routes (web.php):
Route::get('/lang/{locale}', function ($locale) {
session()->put('locale', $locale);
Log::info('session locale : ' . $locale);
App::setLocale($locale);
Log::info('app locale : ' . App::getLocale());
return redirect()->back();
})->name('locale');
Route::get('/test-locale', function () {
dump(session()->all()); // Shows session data
dump(app()->getLocale()); // Intended to show the current app locale
});
Middleware (SetLocale.php):
class SetLocale
{
public function handle(Request $request, Closure $next): Response
{
if (Session::has('locale')) {
$locale = Session::get('locale');
Log::info('session get : ' . $locale);
App::setLocale($locale);
Log::info('app locale : ' . App::getLocale());
}
return $next($request);
}
}
Bootstrap Configuration (bootstrap/app.php):
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__ . '/../routes/web.php',
commands: __DIR__ . '/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->append(\App\Http\Middleware\SetLocale::class);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
When I switch to fr, in the log I get : [2024-03-23 19:47:07] local.INFO: session locale : fr [2024-03-23 19:47:07] local.INFO: app locale : fr
but when i visit /test-locale I see :
array:5 [▼ // routes/web.php:39
"switch_locale_key" => "en"
"_token" => "yzoel19iN5PlZIb0CUEtJGRZ5awKYbqCx5agUOMD"
"locale" => "fr"
"_previous" => array:1 [▶]
"_flash" => array:2 [▶]
]
"en" // routes/web.php:40
Thank you in advance for your help!
Looking at the docs, you are appending to global middleware, but the problem with that is that the session has not yet been started so you cannot read from the user's session.
You need to append to the web middleware group
https://laravel.com/docs/11.x/middleware#laravels-default-middleware-groups
->withMiddleware(function (Middleware $middleware) {
$middleware->web(append: [
\App\Http\Middleware\SetLocale::class,
]);
})
Please or to participate in this conversation.