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

skoobi's avatar
Level 13

Roles using middleware

Hi.

I'm playing around with the middleware and thought that a good bit of practice would be to create a role-based auth system, but am a bit stuck when trying to do multiple roles through the middleware.

What is trying to do is to have something that looks like this in the routes:

Route::resource('users', 'UsersController')->middleware('role:admin,member');

and then something like this in the views:

@if(Auth::user()->hasRole('admin,member'))

And for the CheckUsersRole middleware looks like this at the moment :

public function handle($request, Closure $next, ... $roles)
    {
        foreach ($roles as $role) {
            if (Auth::user()->hasRole($role)) {
                return $next($request);
            }
            return redirect()->route('dashboard')->with(['status' => 'You are not authorised to view this page...', 'alert' => 'warning']);
        }
    }

And the User Model:

    public function hasRole($role)
    {
        if ($this->role_id === $role) {
            return true;
        }
        return false;
    }

But what's happening is that it's not going through the array. It's only showing the first which is admin.

I'm not quite sure how to do the view one yet but will get around to that after the middleware is sorted.

Any help or info would be grateful.

Many thanks

0 likes
2 replies
jlrdw's avatar

I don't know how you store roles, I use comma separated list:

admin,bookkeeper
admin
user
//etc

I use explode to see if a role matches the required role:

    public static function chkRole($role = null)
    {
        $userrole = Auth::user()->role;
        $checkrole = explode(',', $userrole);
        if (in_array($role, $checkrole)) {
            return true;
        }
        return false;
    }

But again I don't know how you store, but maybe you can use in_array somehow.

skoobi's avatar
Level 13

Hi @jlrdw. Thanks for your reply.

The way the roles are set is that I have a list of roles in the database which so 1 => 'admin', 2 => 'member' etc

Ill give the in_array a shot and see if i can just pass the variable through and explode that variable.

Many thanks

Please or to participate in this conversation.