Search code examples
laravel

$request->route() is null in Middleware, how can I filter by route parameters?


Laravel 5.1 deprecates Route::filter() and other related functions, claiming in the docs that:

Route filters have been deprecated in preference of middleware.

But if your route filter accesses route parameters, how can you replace this with middleware, since the $request->route() is null in middleware?

Route::filter('foo', function($route, $request) {
    if ($route->parameter('bar') > 1000) {
         return Redirect::route('large-bars');
    }
});

The closest I can see is something like

class FooMiddleware {
    public function handle($request, Closure $next)
    {
        // Note that $request->route() is null here, as the request
        // hasn't been handled by Laravel yet.

        if ($request->segment(4) > 1000) { // ewww...
            return Redirect::route('large-bars');
        }

        return $next($request);
    }
}

but this is obviously much more brittle than referring to the parameter by name. What am I missing here? Thanks!


Solution

  • $request->route() is only null for global middleware registered in App\Http\Kernel::$middleware. To have access to the current route, instead you must register your middleware in Kernel::$routeMiddleware:

    protected $routeMiddleware = [
        ...,
        'foo' => FooMiddleware::class,
    ];
    

    Proposals to change this behavior have been rejected by the Laravel maintainers due to architectural concerns.