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

时间:2015-08-07 02:25:26

标签: laravel

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!

1 个答案:

答案 0 :(得分:18)

对于在$request->route()中注册的全局中间件,

App\Http\Kernel::$middleware仅为空。要访问当前路由,您必须在Kernel::$routeMiddleware

中注册中间件
protected $routeMiddleware = [
    ...,
    'foo' => FooMiddleware::class,
];

Proposals to change this behavior have been rejected by the Laravel maintainers由于架构问题。