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!
答案 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由于架构问题。