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

rene's avatar
Level 2

MiddleWare for Roles?

Hi, Why isn't this working:

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;

class AdminAuthenticate {

    protected $auth;
    
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;
    }

    public function handle($request, Closure $next)
    {
        if ($this->auth->guest() || $this->auth->role != 'admin')
        {
            if ($request->ajax())
            {
                return response('Unauthorized.', 401);
            }
            else
            {
                return redirect()->guest('auth/login');
            }
        }

        return $next($request);
    }

}

And for the controllers:

public function __construct()
    {
        $this->middleware('authAdmin');
    }

Kernel

protected $routeMiddleware = [
        'auth' => 'App\Http\Middleware\Authenticate',
                'authAdmin' => 'App\Http\Middleware\AdminAuthenticate',
        'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
        'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
    ];

I want a Middleware, so only Users that are logged in and have as role in the Usertable "admin".

0 likes
2 replies
bobbybouwmann's avatar
Level 88

$this->auth->role is nothing, should be something like this: $this->auth->user()->role

1 like
jekinney's avatar

Also if it is a one user to many roles you would need to loop through the user->roles (for each) and perform the if check in side the loop. You can return($next) in the loop and default to return redirect.

I tested using more then one middleware and it worked. So you could use the given authentication middleware and drop the guest check from your middleware.

Please or to participate in this conversation.