Ad

Laravel - Check Account Status When Perform Post Request

- 1 answer

in my user table I have a active_id column to track this user account is still active or not.

Is it possible when a logged in user visit our website, check if it's not a active user then logout the logged in user.

Or when the logged in inactive user perform a post request , log out the user immediately .

Is it possible ?

Ad

Answer

You can accomplish this very easily with Middleware

  • Do the console command php artisan make:middleware CheckUserIsActive

  • Go to the generated file at app/Http/Middlewares/CheckUserIsActive

  • In the handle method

    public function handle($request, Closure $next)
    {
        if (! $user = auth()->user()->is_active) {
            auth()->user()->logout();
        }
        return $next($request);
    }
    
  • Edit the app/Http/Kernel.php file: find web key on middlewareGroups property and append your new middleware \App\Http\Middlewares\CheckUserIsActive::class,

With this approach the check will be fired off on each request on your app, assuming that in your routes.php file you have web group middleware applied to all your routes, which is the case if you installed laravel and didn't change it.

Take a closer look at middlewares in the Documentation


Also note, that this will work only when there is an authenticated user. If there isn't then auth()->user() will return null and you'll get and error like 'Trying to call method logout() on null'. To avoid this error you need to make sure that there is an authenticated user and only then check if he's active. To do so Laravel provides built in auth middleware. Just append it to the middlewaresGroups's web key before your own middleware.

But again this is to work if it's fit your projects needs. If you do require user to be authenticated to go to any of the pages of your app then do this approach. if not - you need to limit some requests to be filtered by middlewares. Again, you may find this on docs or ask here if needed, I'll provide samples

Ad
source: stackoverflow.com
Ad