Steve
Steve

Reputation: 1672

Checking if the user is logged in or not using social authentication

I have a method Where i save the user information after checking if the user is logged in or not :

 public function index()
    {
           if(Auth::check())
            {
                  $newuser=new User();
                  $newuser->username=Auth::user()->username;
                  $newuser->email=Auth::user()->email;
                  $newuser->save();
            }
            else 
            {
                 // not logged in
            }

    }

But, if the user is logged in using social authentication, Auth::check() shows false and else statement is executed. How can i check if the user is logged in using social authentication.Something like:

if(Auth::check() || Socialite::driver('facebook')->user())
{
   // logged in
}
else
{
   // not logged in
}

I can get the name and email with:

$username = Socialite::driver('facebook')->user()->username;
$email = Socialite::driver('facebook')->user()->email;

Upvotes: 2

Views: 2250

Answers (2)

Saumini Navaratnam
Saumini Navaratnam

Reputation: 8870

How about you do Auth::login($fbUser, true); in the social authentication callback. Note $fbUser is the Authenticatable user model. You have to convert the social authentication user details into user model.

In this way Auth::check() and Auth::user() will return the FB user details.

Upvotes: 3

Shubhang Arora
Shubhang Arora

Reputation: 290

If the user is logged in then you can get the user instance like this

$user = Socialite::driver('facebook')->user();

so you function will be

public function index()
{
       $user = Socialite::driver('facebook')->user();
       if($user)
        {
              $newuser=new User();
              $newuser->username=$user->username;
              $newuser->email=$user->email;
              $newuser->save();
        }
        else
        {
             // not logged in
        }

}

so if the user is logged in using the social authentication then

$user = Socialite::driver('facebook')->user();

will get that user instance for you and then you can save details of that user.

Upvotes: 1

Related Questions