Laravel 5.3 从第二次开始记录一个新的 Facebook 用户

Laravel 5.3 logging a new Facebook user from the second time

我正在使用 socialite 将登录与 Facebook 功能集成在一起。这是我的代码:

public function handleProviderCallback()
{

    try {
        $socialUser = Socialite::driver('facebook')->user();
    } catch (\Exception $e) {
        return redirect('/dashboard');
    }


    /*section1 : i check if the user exists in the db, and if no then 
    I save this user in the db */

    $user = User::where('facebook_id', $socialUser->getId())->first();
    if (!$user) {
        User::create([
            'facebook_id' => $socialUser->getId(),
            'name' => $socialUser->getName(),
            'email' => $socialUser->getEmail(),
        ]);

        Auth::loginUsingId($socialUser->id);
        return redirect()->intended('/dashboard');
        }

        /* end of section one */


        else{
        if(Auth::loginUsingId($user->id)){
            return redirect()->intended('/dashboard');
        }
    }


}

问题是:我用新用户登录,数据被添加到数据库,我被重定向到仪表板,但我没有登录。在我再次尝试登录后(当用户已经存在时在数据库中)我成功登录了。为什么?谢谢!

问题出在下一行。您必须传递数据库中的用户 ID,而不是 Facebook ID。

Auth::loginUsingId($socialUser->id);

更新如下

$newUser = User::create(...);
Auth::loginUsingId($newUser->id);