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!
For route specific filtering place the 'Path\To\Middleware', within the middleware array within RouteServiceProvider. php within the App\Providers folder. You can also access the route object via app()->router->getCurrentRoute() .
Creating a basic route group A basic route group in Laravel is created using Route::group() , as shown below. }); The method takes in two parameters, an array, and a callback. The array contains all shared features of the routes in the group.
The Default Route Files The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group.
Laravel routes are located in the app/Http/routes. For instance, to pass in a name parameter to a route, it would look like this. Route::get('/params/{name}', function ($name) { return $name }); By convention, the Controller function accepts parameters based on the parameters provided.
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With