Home » Php » php – Laravel 5 and Socialite, how to save in the database and log-in

php – Laravel 5 and Socialite, how to save in the database and log-in

Posted by: admin July 12, 2020 Leave a comment

Questions:

After reading: http://laravel.com/docs/5.0/authentication I was able to retrieve the user details from the OAuth provider (Facebook) using Socialite:

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

But I couldn’t find any further documentation on how to save the user in the database or log the user in.

I want to do the equivalent to:

Auth::attempt(['email' => $email, 'password' => $password])

But for the details retrieved via Socialite (I don’t have a password)

Can you please show me an example on using “Auth” with user data retrieved via Socialite?

How to&Answers:

Add to “users” table new column: facebook_user_id. Every time when user tries to login through Facebook, Facebook will return the same user id.

public function handleProviderCallback($provider)
{
    $socialize_user = Socialize::with($provider)->user();
    $facebook_user_id = $socialize_user->getId(); // unique facebook user id

    $user = User::where('facebook_user_id', $facebook_user_id)->first();

    // register (if no user)
    if (!$user) {
        $user = new User;
        $user->facebook_id = $facebook_user_id;
        $user->save();
    }

    // login
    Auth::loginUsingId($user->id);

    return redirect('/');
}

How Laravel Socialite works?

public function redirectToProvider()
{
   // 1. with this method you redirect user to facebook, twitter... to get permission to use user data
   return Socialize::with('github')->redirect();
}

public function handleProviderCallback()
{
   // 2. facebook, twitter... redirects user here, where you write code to log in user
   $user = Socialize::with('github')->user();
}