Search code examples
phplaravelauthenticationlaravel-8middleware

Laravel- Auth::check returns false in the middleware for successfull login


My login controller

public function authenticate(Request $request)
    {
        $credentials = $request->validate([
            'username' => ['required'],
            'password' => ['required'],
        ]);

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();
            
            return redirect()->intended('/');
        }

        return back()->withErrors([
            'error' => 'The provided credentials do not match our records.',
        ]);
    }

middleware that i check the auth

class AuthorizeUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::check()) {
            return $next($request);
        } else {
            return view('application');
        }
    }
}

Auth::check() in this middleware returns false event the Auth::attempt was successful. How do I find the cause of this issue?


Solution

  • Thank you all who supported. Problem was with my session configurations. I have previously set session driver as database and changed the session name also. I replaced session.php and .env by default configuration. Then above code worked perfectly. (I guess something went wrong with the session configuration and I will keep posted when I have time to look back that issue)