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

deladels's avatar

Middleware for roles not working as supposed to.

SO I am trying to implement some ACL in a project I am working on through middlewares but the middlewares don't seem to do the checks.

Admin Middleware:

class AdminRole
{
    public function handle($request, Closure $next)
    {
        if (Auth::user()->hasRole('Admin')) {
            return redirect()->intended();

        }

        return $next($request);
    }
}

In my controller in do this to apply the admin middleware :

    public function __construct()
    {
        $this->middleware(['auth', 'admin']);
    }

On my user model, I have this function to check for user role which gets me the correct role when I dd :

//NB:  a user has many roles

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

        return false;
    }

But while testing this out, I noticed I am still able to view the page even if I am not an admin. What could be the problem?

0 likes
3 replies
bobbybouwmann's avatar

Because you redirect to the intended URL. This URL is most of the time the URL before you got redirected to the login screen. Since you don't want to allow the user to have access you should redirect them to a page where they can actually login

class AdminRole
{
    public function handle($request, Closure $next)
    {   
        if (Auth::user()->hasRole('Admin')) {
            return redirect('/login');
        }

        return $next($request);
    }
}
deladels's avatar

@bobbybouwmann Thanks. But I have other roles and what I want to do is check if the user has a particular role. If they do, then they are redirected to the "intended" URL, if they don't have that role, then they are redirected back.

bobbybouwmann's avatar

In that case you need to do this

class AdminRole
{
    public function handle($request, Closure $next)
    {   
        // Redirect if you don't have the role
        if (!Auth::user()->hasRole('Admin')) {
            return redirect('/login');
        }

        // Continue to the intended URL
        return $next($request);
    }
}

Please or to participate in this conversation.