如何覆盖已分配为组中间件的 Laravel 中间件的参数?

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

我有一个接受参数的 Laravel 中间件。该中间件被分配给组级别的一组路由。我需要专门为该组内的单个路由覆盖参数。我该怎么做?

如果我将 ->middleware('my_middleware:new_param') 添加到特定路由,则中间件会执行两次:第一次使用组级别的默认参数,第二次使用新参数。

如果我添加 ->withoutMiddleware('my_middleware')->middleware('my_middleware:new_param') 那么中间件根本不会执行。

例子

\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']);

答案很简单:还必须重复 ->withoutMiddleware 中不想使用的确切参数。这意味着

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']);

成功了。