Lumen middleware sort (priority) Lumen middleware sort (priority) laravel laravel

Lumen middleware sort (priority)


I don't think this is possible in Lumen in the way you want to. What I suggest is using the middleware alongside the router group middleware options.


Remove the global middleware registration

/bootstrap/app.php

$app->middleware([    //App\Http\Middleware\AuthTokenAuthenticate::class]);

Add both middlewares to the route middleware

/bootstrap/app.php

$app->routeMiddleware([    'auth.token' => Vendor\Utilities\Middleware\AuthToken::class,    'auth.token.authenticate' => App\Http\Middleware\AuthTokenAuthenticate::class]);

Create two route groups: one with just auth.token.authenticate and one group with both auth.token and auth.token.authenticate.

/routes/web/php

$router->get('/', ['middleware' => 'auth.token.authenticate', function () use ($router) {    // these routes will just have auth.token.authenticate applied}]);$router->get('/authenticate', ['middleware' => 'auth.token|auth.token.authenticate', function () use ($router) {    // these routes will have both auth.token and auth.token.authenticate applied, with auth.token being the first one}]);

I think this is the cleanest way to get the desired effect.


As of now with Lumen v6 (and possibly earlier), you can specify the middleware as an array field when defining your route. In the routes file web.php, I have something like the following:

$router->get('/api/path/to/thing', [    'uses' => 'FooController@index',    'middleware' => ['etag', 'caching', 'bar']]);

Note how the the middleware field is an array with three elements. When this route is called, the middleware etag will execute first, then caching, then bar, in that order. When you only have a single middleware class, you can either specify it as a plain string or an array with just one element. This can of course be extended to route groups so that you have an entire class of routes that all use this middleware in this order.