Home > Net >  How to overwrite parameters of a Laravel middleware which already is assigned as a group middleware?
How to overwrite parameters of a Laravel middleware which already is assigned as a group middleware?

Time:12-28

I have a Laravel middleware which accepts parameters. This middleware is assigned to a group of routes on the group level. I need to overwrite the parameters specifically for a single route inside this group. How do I do this?

If I add ->middleware('my_middleware:new_param') to the specific route, then the middleware is executed twice: first with the default parameters from the group level, second with the new parameter.

If I add ->withoutMiddleware('my_middleware')->middleware('my_middleware:new_param') then the middleware is not executed at all.

Example

\App\Http\Kernel:

class Kernel extends HttpKernel {
  protected $middleware = [
    ...
  ];

  protected $middlewareGroups = [
    'my_middleware_group' => [
      'my_middlware:default_param',
      ...,
    ],
  ];

  protected $routeMiddleware = [
    'my_middlware' => \App\Http\Middleware\MyMiddleware::class,
    ...
  ];
}

\App\Providers\RouteServiceProvider:

class RouteServiceProvider extends ServiceProvider {
  public function boot() {
    $this->routes(function () {
      Route::middleware('my_middleware_group')
        ->group(base_path('routes/my_routing_group.php'));
    });
  }
}

routes/my_routing_group.php:

// Neither the following line
Route::get('/my-url', [MyController::class, 'getSomething'])->middleware(['my_middlware:new_param']);
// nor this line works as expected
Route::get('/my-url', [MyController::class, 'getSomething'])->withoutMiddleware('my_middleware')->middleware(['my_middlware:new_param']);

CodePudding user response:

The answer is simple: One must also repeat the exact parameters in ->withoutMiddleware which one want not to use. This means

routes/my_routing_group.php:

Route::get('/my-url', [MyController::class, 'getSomething'])
  ->withoutMiddleware(['my_middlware:default_param'])   // the original parameters must be repeated, too
  ->middleware(['my_middlware:new_param']);

does the trick.

  • Related