PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, January 8, 2022

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

 January 08, 2022     laravel, laravel-8, laravel-middleware, php, url-routing     No comments   

Issue

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

Solution

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.



Answered By - user2690527
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing