Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

WimN's avatar
Level 5

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

0 likes
4 replies
WimN's avatar
Level 5

This worked for me:

		$request->mergeIfMissing(['lang' => $lang]);

So to set the variable in the middleware:

	 public function handle(Request $request, Closure $next): Response
		{
	     if(!auth()->check()){
	     $lang = 'en';
	    } else {
 		    $lang = auth()->user()->lang; };
	      $request->mergeIfMissing(['lang' => $lang]);
  		   return $next($request);
	 }

From there on i can call the value:

							$lang = $request->input('lang');
1 like
krisi_gjika's avatar
public function handle(Request $request, Closure $next): Response
{
    $lang = auth()->check() ? auth()->user()->lang : config('app.locale');
    
    app()->setLocale($lang);
  	return $next($request);
}
1 like
martinbean's avatar
Level 80

@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.

1 like

Please or to participate in this conversation.