0

Laravel does not save my session after auth()->login()

Hello. I'm using Socialite to create Google login in Laravel application, the redirect and callback functions worked fine. But I am having some trouble in login session, Laravel did not save my session after calling Auth::login(), and Auth::user() returns null, but Auth::user() still works in the function (controller action) where Auth::login() called. Can someone help me?

class LoginController extends Controller
{
    public function callback(Request $request) {
        $googleUser = Socialite::driver('google')->user();
        $userLogin = [
            'id' => $googleUser->getId(),
            'name' => $googleUser->getName(),
            'email' => $googleUser->getEmail(),
            'avatar' => $googleUser->getAvatar(),
        ];
        $email = $userLogin['email'];
        $user = User::updateOrCreate(
            ['email' => $email],
            $userLogin
        );
        auth()->login($user);
        // This still working.
        // dd(auth()->user());
        return redirect()->route('debug');
    }
}

But it wasn't work in another controller action

class DebugController extends Controller {
    public function __invoke() {
        $user = auth()->user();
        // This returns null
        dd($user);
    }
}
7
  • It seems like the session is not persisting the login. Have you search for answers to similar questions posted on SO? E.g. is your middleware configured correctly as described here?
    – Tony
    Commented May 4 at 9:48
  • Yes but all answers in that post are useless
    – Võ Bảo
    Commented May 4 at 10:08
  • Is that "yes, I've searched" or "yes, the middleware is configured correctly"? Apologies, I should only ask one question at a time.
    – Tony
    Commented May 4 at 10:11
  • Yes, I have looked that post sir
    – Võ Bảo
    Commented May 4 at 10:12
  • Have you configured your middleware to use Auth?
    – Tony
    Commented May 4 at 10:14

0

Browse other questions tagged or ask your own question.