Home > Software engineering >  Same route different middleware route group
Same route different middleware route group

Time:06-05

Here is my super admin middleware,

if(Auth::user()->role_id == 1) {
    return $next($request);
}
return redirect('/');

and,here is admin middleware,

if(Auth::user()->role_id == 2) {
    return $next($request);
}
return redirect('/');

Here is my manager middleware,

if(Auth::user()->role_id == 3) {
    return $next($request);
}
return redirect('/');

Here is my seller middleware,

if(Auth::user()->role_id == 4) {
    return $next($request);
}
return redirect('/');

and, this is web.php,

Route::middleware(['superadmin'])->group(function () {

    Route::resource('users', UserController::class);
    //and more
});
Route::middleware(['admin'])->group(function () {

    Route::resource('users', UserController::class);
    //and more
});
Route::middleware(['manager'])->group(function () {

    Route::resource('managers', ManagerController::class);
    //and more
});
Route::middleware(['seller'])->group(function () {

    Route::resource('sellers', SellersController::class);
    //and more
});

I have 4types of middleware. Each route group have different route. Its working properly. Some of the routes are also used in another group. But then it doesn't work.

CodePudding user response:

Doesn't make sense to have two different middleware here. What do you want to achieve? If the user is an admin then what and if user is a superadmin then what?

If the purpose is to just allow either admin or superadmin to access routes defined under the middleware group then a single middleware is enough.

//IsAdmin middleware
//if the user is either superadmin or admin allow else redirect
if(in_array(Auth::user()->role_id, [1,2])) {

    //If you want to process based on whether admin or superadmin
    //you can do it here
    //if(Auth::user()->role_id ===1) {
    //    process when user is superadmin
    // }
    //else {
    //    process when user is admin
    //}
    return $next($request);
}
return redirect('/');

Then protect the routes in routes file

Route::middleware(['isAdmin'])->group(function () {

    Route::resource('users', UserController::class);

});
  • Related