简体   繁体   中英

Laravel 8 same route multiple middleware using OR condition

Hello i tried to use middleware like the code below to validate OR operator

Route::get('/page', [Controller::class, 'index'])->middleware(['mid1','mid2']);

in this example it uses the AND operator not OR I used also groups like this

Route::group(['middleware' => 'mid1'], function () {
   Route::get('/page', [Controller::class, 'index']);
});
Route::group(['middleware' => 'mid2'], function () {
   Route::get('/page', [Controller::class, 'index']);
});

but using groups with same route the second route in the group is the only one readable. Any help please

There's nothing builtin in laravel to do such a thing.

You can create another middle-ware to contain both conditions you need to apply.

In you middleware:

public function handle($request, Closure $next) {
    if (condition1 || condition2) {
       return $request($next);
    }
    abort('statusCode');
}

I agree with @Faesal. It would be best to combine two middleware logic into one middleware.

public function handle($request, Closure $next) {
    if (your condition) {
       //logic inside mid1 handler
    }else{
       //logic inside mid2 handler
    }
}

Although it is not recommended but you can put your conditions in route file.

if(your conditions){
  Route::group(['middleware' => 'mid1'], function () {
   Route::get('/page', [Controller::class, 'index']);
  });
}else{
 Route::group(['middleware' => 'mid2'], function () {
   Route::get('/page', [Controller::class, 'index']);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM