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

NetoPVH's avatar

Middleware Before Auth

Hello guys,

to a problem and I would love you to help me ... I created a middleware to check the user's role .. more this middleware must be performed only after the user made ​​the sign ... how should I complete this middleware ?

Thanks

0 likes
7 replies
ctroms's avatar

Are you trying to execute more middleware only if the user has the given role or check the role of a user after they are authenticated?

NetoPVH's avatar

The User will authenticate with login and password for LDAP , further authenticate the middleware will check if it has any linked paper, if not anger assign the role of common ... User middleware will make this check.

$roles = User::find(auth()->user()->id)->roles;
ctroms's avatar

I see what your code is doing but I'm still having a little difficulty with your description. What is linked paper, and anger?

NetoPVH's avatar

The user never accessed the system , the first access it has no role , then you will atrubuido the common user role ... the middleware does this check and assign the role to him ... however this check must be made after the authentication...

     $user = User::find(auth()->user()->id);

            $role = Role::find(2);

            $user->roles()->attach($role);
NetoPVH's avatar

my difficulty and make this middleware run only after the authentication ... how do ?

thomaskim's avatar

Just run the middleware after auth.

Route::get('/', ['middleware' => ['auth', 'yourCustomMiddleware'], function () {
    // 
}]);
ctroms's avatar
ctroms
Best Answer
Level 15

@thomaskim Beat me to it.

@NetoPVH Assuming that 2 is the id of your common role, your middleware could have a handle method like:

public function handle($request, Closure $next)
{
    if (Auth::user()->roles()->count() == 0) {
        Auth::user()->roles()->attach(Role::find(2));
    }

    return $next($request);
}

If you run the middleware after auth as @thomaskim suggests, this middleware will only run if the user is authenticated and the user doesn't have any roles assigned.

Also make sure you import the Auth facade or assign your user variable as you did before.

use Illuminate\Support\Facades\Auth;

class YourMiddlewareClass {
1 like

Please or to participate in this conversation.