skip to Main Content

In laravel I am trying to get the current user after logged in but I can’t. Why I can’t get the current user which is already logged in?

public function login(Request $request)
{
    if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
        $user = Auth::user();
        Auth::login($user);
        return ['message' => "Successfully Logged In"];
    }
    return ['error' => "Invalid Credentials"];
}

public function currentUser()
{
    $user = Auth::user();
    if ($user) {
        return ["user" => $user];
    }
    return ["error" => "User Not Found"];
}

'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    ],

Route::post('/login',[UserController::class, 'login']);
Route::get('/getuser',[UserController::class, 'currentUser']);

2

Answers


  1.  use IlluminateSupportFacadesAuth;
     use IlluminateHttpRequest;
    
     public function login(Request $request)
        {
            if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
                // If the login is successful, it's advisable to refresh the user's session to safeguard against session fixation.
                $request->session()->regenerate();
                // Authentication was successful, no need to call Auth::login($user)
                return ['message' => "Successfully Logged In"];
            }
            return ['error' => "Invalid Credentials"];
        }
    

    You get the current logged in user by calling auth()->user();. To get logged in user email in blade use {{ auth()->user()->email }}

    Login or Signup to reply.
  2. You don’t need to call Auth::login($user) after using Auth::attempt because the attempt method already logs in the user if the credentials are correct. Make sure the guards are working correctly. If they are not, follow the solution mentioned above to regenerate the session."

     $request->session()->regenerate();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search