I have this middleware to change the application’s language based on the user’s language:
public function handle(Request $request, Closure $next): Response
{
if (Auth::check()) {
$user = Auth::user();
$languageText = $user->language_text;
$language = $this->languageMapping[$languageText] ?? 'en';
if (in_array($language, ['en', 'fr', 'de', 'it'])) {
App::setLocale($language);
session(['locale' => $language]);
} else {
App::setLocale('en'); // Default language
session(['locale' => 'en']);
}
} else {
App::setLocale(session('locale', 'en')); // Default language
}
return $next($request);
}
Im’ working with laravel 11, no kernel.php…
this is my 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->alias([
'role' => CheckRole::class
]);
$middleware->append(SetUserLanguage::class);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
The middleware works, but Auth::check()
gives me always false and also Auth::user()
is always null. The session works, I tried with static datas and the language changed.
I can I manage with Auth()?
3