Search code examples
laravelauthenticationlaravel-authentication

laravel: how to stay login until a condition becomes false?


I have a field (can_login) in my users table.

normally,users can login. and logout with this code:

 Auth::logout();

I want, when each time a logged-in user refresh a page, laravel check can_login in user table. if can_login is false, then auto logout.

I try this in RouteServiceProvider

public function boot()
{
   parent::boot();
   if(auth()->user()->can_login){
       return route('logout');
   }
}

but auth()->user() is always empty.


Solution

  • You can use a middleware or add a check to your existing authentication middleware. On each request it passes through a middleware to check if user is authenticated and after that auth()->user() will not be empty.

    Simplest solution would be to create a middleware in app/Http/Middlewares/CheckUserCanLoginMiddleware.php

    class CheckUserCanLoginMiddleware
    {    
        public function handle(Request $request, Closure $next)
        ) {
            if ($request->user()->can_login ?? false) {
                Auth::logout();
                return $this->sendUnauthorizedResponse();
            }
    
            return $next($request);
        }
    }
    

    And then register it as a routeMiddleware` in your bootstrap/app.php file.

    The last thing you need is to use it to our routes middlewares after authentication middleware.