为什么我不能使用laravel使用oauth登录来存储facebook id和avatar路径?

时间:2016-05-30 15:34:07

标签: php facebook laravel oauth laravel-socialite

我正在使用Socialite登录/注册Facebook进入我的应用程序。当我转储我的$ facebookUser变量时,我看到这个json:

$ facebookuser:

enter image description here

但是当我尝试存储ID和头像时,它并不存储它,我无法显示Facebook的用户个人资料图片。我正在使用laravel来存储我的用户。

AuthController.php:

public function handleProviderCallback()
{
    try {
        $user = Socialite::driver('facebook')->user();
    } catch (Exception $e) {
        return redirect('auth/facebook');
    }

    $authUser = $this->findOrCreateUser($user);

    Auth::login($authUser, true);

    return redirect()->route('home')->with('successfullFacebookLogin', Auth::user()->name);
}

private function findOrCreateUser($facebookUser)
{
    // When I dd($facebookuser) it gives json stated above
    $authUser = User::where('facebook_id', $facebookUser->id)->first();

    if ($authUser){
        return $authUser;
    }

    return User::create([
        'name' => $facebookUser->name,
        'email' => $facebookUser->email,
        'facebook_id' => $facebookUser->user['id'],
        'avatar' => $facebookUser->avatar,
        'facebookAccount' => 1

    ]);
 }

1 个答案:

答案 0 :(得分:1)

使用Laravel Socialite提供的方法来访问用户详细信息而不是直接访问该属性,以下是所有内置提供程序的可用方法列表:

$user->getId();
$user->getNickname();
$user->getName();
$user->getEmail();
$user->getAvatar();

所以你的代码应该是:

private function findOrCreateUser($facebookUser)
{
    // When I dd($facebookuser) it gives json stated above
    $authUser = User::where('facebook_id', $facebookUser->id)->first();

    if ($authUser){
        return $authUser;
    }

    return User::create([
        'name' => $facebookUser->getName(),
        'email' => $facebookUser->getEmail(),
        'facebook_id' => $facebookUser->getId(),
        'avatar' => $facebookUser->getAvatar(),
        'facebookAccount' => 1

    ]);
 }

请勿忘记在$fillable模型的User属性中列出上述列:

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password', 'facebook_id', 'avatar', 'facebookAccount'
];

否则手动填写属性:

$user = new User;
$user->name = $facebookUser->getName();
$user->email = $facebookUser-> getEmail();
$user->facebook_id = $facebookUser->getId();
$user->facebookAccount = 1;
$user->save();

return $user;