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

amitsolanki24_'s avatar

$request->route() returns null in laravel 11 why?

#$request->route() returns null in laravel 11 why?

$request->route() returns null in laravel
or
request()->route() returns null in laravel

but its working in old version.

Note: I'm executing this code in custom middleware
0 likes
13 replies
amitsolanki24_'s avatar

@jlrdw yes I have registered.

->withMiddleware(function (Middleware $middleware) {
    $middleware->append([
        SetLocaleMiddleware::class
    ]);
})
rodrigo.pedra's avatar

@amitsolanki24_

$middleware->append() will append the middleware to the global middleware stack, which runs before the route object is bound to the request object.

Try appending to the web middleware group instead:

$middleware->appendToGroup('web', [
    SetLocaleMiddleware::class
]);

If you use more middleware groups, you'll need to append it to each group.

2 likes
amitsolanki24_'s avatar

@martinbean I want to filter some routes if current route name is exists in allowed routes group array then return request after converting current page into another language otherwise abort 404.

This is a custom middleware for changing pages into different language.

amitsolanki24_'s avatar

@JussiMannisto Sure, here ia my code, sorry for late response actually I was busy in other stuff.

    public function handle($request, Closure $next)
    {

        $valid_routes = [
            ..,
			...
        ];

        if (!request()->routeIs($valid_routes)) {
            // when user request spanish page that are not exists in spanish
			abort_if(request()->route()->getPrefix() == '/es,  404);	
            app()->setLocale('en');
        } else if (Cookie::has('user_preferred_language')) {
            app()->setLocale(request()->route()->getPrefix() == '/es' ? 'es' : 'en');
        }
        return $next($request);
    }
amitsolanki24_'s avatar

@MohamedTammam These are returning null in custom middleware

    		$route = Route::current(); // Illuminate\Routing\Route
   		    $name = Route::currentRouteName(); // string
        	$action = Route::currentRouteAction(); // string
1 like
MohamedTammam's avatar

@amitsolanki24_ Can you try adding your middleware like this:

$middleware->appendToGroup('web', [
        SetLocaleMiddleware::class
]);	
1 like
amitsolanki24_'s avatar
amitsolanki24_
OP
Best Answer
Level 8

@MohamedTammam I have fixed this issue.

by adding this line in web.php file

Route::prefix($prefix)
    ->middleware(SetLocaleMiddleware::class)

and removing custom middleware from bootstrap/app.php file

 $middleware->append(SetLocaleMiddleware::class);

Please or to participate in this conversation.