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
You get the current logged in user by calling
auth()->user();
. To get logged in user email in blade use{{ auth()->user()->email }}
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."