Search code examples
laravelmiddleware

Auth::check fails in middleware


Can somebody explain why this strange behavior of Laravel is happening? Basically, I am trying to create a middleware for my application

 public function handle(Request $request, Closure $next)
    {
        if (auth()->check()) {

            $expires = Carbon::now()->addMinute(2);
            \Illuminate\Support\Facades\Cache::put('user-is-online-' . Auth::user()->id, true, $expires);
        }
        return $next($request);
    }
}

But auth()->check it is keep failing and not returning true , (user is authenticated) , auth()->check is working in other places like web routes and controllers method but why not here ?


Solution

  • If you are using auth middleware to protect your routes, then make sure this auth middleware is set to run before your middleware, otherwise auth()->check() will return false. Try php artisan route:list and check the orders of middlewares for your specified route.