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

MahmoudAdelAli's avatar

Should i check if the user auth in middleware

When i create role middle-ware like SuperAdmin Midddleware, i found this result from the search

public function handle($request, Closure $next, ... $roles)
{
    if (!Auth::check()) // I included this check because you have it, but it really should be part of your 'auth' middleware, most likely added as part of a route group.
        return redirect('login');

    $user = Auth::user();

    if($user->isAdmin())
        return $next($request);

    foreach($roles as $role) {
        // Check if user has the role This check will depend on how your roles are set up
        if($user->hasRole($role))
            return $next($request);
    }

    return redirect('login');
}

so i create some think like that .

class SuperAdminRoleMiddleware
{
    public function __construct($request,Closure $next)
    {
        if (!Auth::check()){
             return redirect('login');
        }
        return $next($request);
    }

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

    }
}

but in my web i can use auth middleware right ? , the question here should i check for the auth like that ?

0 likes
2 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

It is generally best practice to check for authentication in a separate middleware, rather than within the middleware that is responsible for checking roles. This is because authentication is a separate concern from authorization, and it is better to keep them separate.

For example, you could create an Authenticate middleware that checks for authentication, and then use that middleware in the route group that contains the SuperAdminRoleMiddleware middleware. This way, you can ensure that authentication is checked before authorization.

// Authenticate middleware
public function handle($request, Closure $next)
{
    if (!Auth::check())
        return redirect('login');

    return $next($request);
}

// SuperAdminRoleMiddleware middleware
public function handle($request, Closure $next)
{
    if (Auth::user()->hasRole('SuperAdmin'))
    {
        return $next($request);
    }
    return redirect('/');

}
1 like
MahmoudAdelAli's avatar

@LaryAI Thank you this is very helpful , but i had another question excuse me , i had error

Unresolvable dependency resolving [Parameter #0 [ <required> $request ]] in class App\Http\Middleware\SuperAdminRoleMiddleware

after i removed the __construct , every thing is working correctly , so where's the problem here ? and the error marked this line

  return $next($request);

Please or to participate in this conversation.