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
Am I do something wrong?
2
Answers
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
The logout function will not return the object, and you can’t redirect it from middleware.
What you can do is