I was working on adding localization to my Laravel 11 project, and I created a middleware called SetLocale
that consists of the codebase similar to below:
public function handle(Request $request, Closure $next): Response
{
App::setLocale(session()->get('locale'));
return $next($request);
}
I added it to my bootstrap/app.php
file like this:
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(SetLocale::class);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
In my LocalizationController, I set the session like this:
public function setLocalization(string $locale): RedirectResponse
{
session()->put('locale', $locale);
App::setLocale($locale);
return back();
}
My route in web.php
looks like this:
Route::get('/locale/{locale}', [LocalizationController::class, 'setLocalization'])->name('locale.switch');
Here’s what I tried:
- Used the Session facade throughout the codebase, but it didn’t work.
- Used
back()->with('locale', $locale);
when returning in thesetLocalization()
function in the LocalizationController, but it didn’t work. - Tried various changes, but I couldn’t retrieve the ‘locale’ session data in my middleware.
Unfortunately, it’s not working as expected.
The only way I got it to work was by wrapping the middleware around the route like this:
Route::prefix('localization')->middleware([SetLocale::class])->group(function() {
Route::get('/locale/{locale}', [LocalizationController::class, 'setLocalization'])->name('locale.switch');
});
Is my use of global middleware incorrect, or did Laravel change how it handles sessions for global middleware?
Just an FYI, Laravel has now moved its middleware to elsewhere. Now it’s a clean file located in the bootstrap/app.php file.
Thanks for your help.
Sreekesh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.