skip to Main Content

I want make a middleware in my Laravel 9 project. What I want is if the user is not active, they’re automatically logout. In my middleware class like this :

public function handle(Request $request, Closure $next)
{
    if (Auth::user()->is_active != 1) {
        return Auth::logout();
    }
    return $next($request);
}

But when I try it, I’m getting error like this

error laravel

Am I do something wrong?

2

Answers


  1. You’re pretty close, just some minor changes are needed.

    So the problem is that your middleware would usually return the $next($request);, otherwise it would break Laravel’s internal pipeline (You can read this good blog post to understand more about middleware and pipelines Understanding Laravel Pipelines).

    But returning that will probably not work in your case since your auth middleware must have already been executed before this.

    The easiest way to handle this would be to logout and abort (Assuming that returning a 401 response is what you would like in this scenario), something like

    public function handle(Request $request, Closure $next)
    {
        if (Auth::user()->is_active != 1) {
            Auth::logout();
            abort(401, 'User is not active');
        }
        return $next($request);
    }
    
    Login or Signup to reply.
  2. The logout function will not return the object, and you can’t redirect it from middleware.

    What you can do is

    public function handle(Request $request, Closure $next)
    {
        if (Auth::check() && Auth::user()->is_active != 1) {
            Auth::logout();
            return redirect('/login'); # add you login route
        }
        return $next($request);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search