Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 540
Ben Claar Avatar asked Aug 07 '15 02:08

Ben Claar


People also ask

How do I find my middleware route?

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() .

How to group routes in Laravel?

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.

What are the default route files in Laravel?

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.

How do I get params in Laravel?

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.


1 Answers

$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.

like image 89
Ben Claar Avatar answered Sep 23 '22 17:09

Ben Claar