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

sherwinmdev's avatar

modify auth middleware to force a user logout in laravel 5.4?

i need a way to force a logged in user to get logged out. i have a field users.is_active that takes 'Y' o r 'N' values. as admin, i can modify that value. if i change the value 'N' and they have an active session, i'd like for them to get logged out as soon as the auth middleware is envoked again.

i'd like to implement this http://stackoverflow.com/a/37876712/3893181 but i the auth middleware is now located in Illuminate\Auth\Middleware\Authenticate. do i copy it in /app/Http/Middleware/Authenticate.php and add my conditional statement?

i want the default functionality to continue to work but add that extra check.

0 likes
2 replies
ricardoarg's avatar
Level 8

just create ANOTHER middleware that checks that field in the logged in user. If it's "N", then do the logout, or redirect:

artisan make:middleware CheckIsActive

then in \app\http\Kernel.php, in the $routeMiddleware array, add:

'isActive' => \App\Http\Middleware\CheckIsActive::class,

then in \app\http\Middleware\CheckIsActive.php, something like this in the handle method (just use boolean and not N/Y, but whatever..):

        if(!$request->user()->is_active == 'N')
        //logout, redirect wherever you want, etc.
        }
    return $next($request);

then, you apply that middleware too the routes you want. if it's applicable to all the routes, you could do something like this in web.php

Route::group(['middleware' => 'isActive'], function () {
    //all your protected routes
});
sherwinmdev's avatar

@ricardoarg thanks, i was hoping to just attach to the existing auth middleware but this works as well. i created a middleware and added it to the web middleware group. i was trying to add it to the global but i guess auth status can't be determined at that stage. the middleware should only logout users who are logged in and have a is_active != 'Y'. otherwise it should allow the next request. here's the code i ended up with.

public function handle($request, Closure $next)
    {
        if (Auth::check())
        {
            if (Auth::User()->is_active != 'Y')
            {
                Auth::logout();
                return redirect()->to('/')->with('warning', 'Your session has expired because your account is deactivated.');
            }
        }
        return $next($request);
    }

Please or to participate in this conversation.