Search code examples
phpfacebooklaraveloauthlaravel-socialite

Why can't I store facebook id and avatar path with oauth login using laravel?


I am using Socialite to login/register with facebook into my application. When I dump my $facebookUser variable I see this json :

$facebookuser :

enter image description here

But when I try to store the id and avatar , it doesn't store it and I can't display the users profile picture of facebook. I am using laravel to store my user.

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

    ]);
 }

Solution

  • Use Laravel Socialite provided methods to access user details rather than access the property directly, here is list of available methods for all built-in providers:

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

    So your code should be:

    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
    
        ]);
     }
    

    Don't forget to state those columns above in $fillable property of User model:

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

    Otherwise fill the attributes manually:

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