Laravel 5.1弃用了Route::filter()
和其他相关函数claiming in the docs that:
但是,如果您的路由过滤器访问路由参数,那么由于中间件中的$request->route()
是null
,您怎么用中间件替换它呢?
Route::filter('foo', function($route, $request) {
if ($route->parameter('bar') > 1000) {
return Redirect::route('large-bars');
}
});
我能看到的最接近的东西是
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);
}
}
但这显然比通过名称引用参数要脆弱得多。我在这里想念什么?谢谢!
最佳答案
对于在$request->route()
中注册的全局中间件,App\Http\Kernel::$middleware
仅为null。要访问当前路由,必须在Kernel::$routeMiddleware
中注册中间件:
protected $routeMiddleware = [
...,
'foo' => FooMiddleware::class,
];
Proposals to change this behavior have been rejected by the Laravel maintainers由于体系结构方面的考虑。