Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Deekshith's avatar

Pass multiple roles in controller construct to middleware

I have a role based middleware like below,

public function handle(Request $request, Closure $next, $role)
    {   
        if (! $request->user()->hasRole($role)) {
            abort(401, 'This action is unauthorized.');
        }
        return $next($request);
    }

and User.php

public function authorizeRoles($roles)
    {
      if ($this->hasAnyRole($roles)) {
        return true;
      }
      abort(401, 'This action is unauthorized.');
    }

    public function hasAnyRole($roles)
    {
      if (is_array($roles)) {
        foreach ($roles as $role) {
          if ($this->hasRole($role)) {
            return true;
          }
        }
      } else {
        if ($this->hasRole($roles)) {
          return true;
        }
      }
      return false;
    }

    public function hasRole($role)
    {
      if ($this->roles()->where('name', $role)->first()) {
        return true;
      }
      return false;
    }

Now in controller i have added like below,

$this->middleware('CheckRole:Admin');

Now i want add another role permission for same midleware like below,

$this->middleware('CheckRole:Admin,JournalAdmin');

but it taking only first parameter which is Admin.

i tried to add like below in web group too.

Route::group([ "middleware" => "CheckRole:Admin,JournalAdmin"], function() {
    Route::get('dashboard',[AdminDashboardController::class,'getAdminDashboard']);
    });

But it is not working. if user has any one role which matches the middleware parameter then it should allow, please help me

0 likes
5 replies
siangboon's avatar

I think you may direct checking the current authenticated user something like this auth()->user()->isAdmin() instead passing parameter for checking...

1 like
MichalOravec's avatar
Level 75
public function handle(Request $request, Closure $next, ...$roles) 
{
    // now you have $roles as an array
}
Deekshith's avatar

@michaloravec Thank you it helped and i solved by calling different function in middleware like below,

public function handle(Request $request, Closure $next, ...$role)
    {   
        if (! $request->user()->authorizeRoles($role)) {
            abort(401, 'This action is unauthorized.');
        }
        return $next($request);
    }
Deekshith's avatar

@michaloravec this one is working fine if i have to match roles in single table. but i want to pass permission parameter too so once role is matched then permission to that role will be checked based on paramter. how to pass another parameter ? if use above method then all parameters will treat as array.

i want to pass like below,

$this->middleware('CheckRole:Admin,JournalAdmin,can_edit_journal');

last parameter which is can_edit_journal is different. Any help?

Please or to participate in this conversation.