Please format your code.
Pass Variable from global middelware to route
Hi,
I have my views in subfolders organised by language e.g. /en or /fr. With global middelware I want to check if the user is logged in and if not the default views will be in english otherwise the language of the user as specified in the user-table.
My middleware works when dd the variable $lang:
public function handle(Request $request, Closure $next): Response
{
if(!auth()->check()){
$lang = 'en';
} else {
$lang = auth()->user()->lang;
}
dd($lang);
}
But fails when going to the next step :
Route::get('/route', function(Request $request) {
return view ($lang.'/route');
}
How can I pass the variable $lang from my middleware to my route?
Thanks in advance
@wimn Make use of Laravel’s existing HasLocalePreference preference, then use it to set the application locale if there is a user:
class SetLocalePreference
{
public function handle(Request $request, Closure $next)
{
if ($user = $request->user()) {
App::setLocale($user->preferredLocale());
}
return $next($request);
}
}
Far fewer lines of code, and no “merging” request data-that-isn’t-actually-request-data.
Please or to participate in this conversation.