0

I have a code like this:

public function createOrGetUser(Provider $provider)
{
    $providerUser = $provider->user();
    $providerName = class_basename($provider);
    $token = $providerUser->token;
    $account = SocialAccount::whereProvider($providerName)
        ->whereProviderUserId($providerUser->getId())
        ->first();
    if ($account) {
        return $account->user;
    }else{
        $account = new SocialAccount([
            'provider_user_id' => $providerUser->getId(),
            'provider' => $providerName
        ]);
        $user = User::whereEmail($providerUser->getEmail())->first();
        if($user->first()) {
        if($providerName == "FacebookProvider") {
            $user->facebook_token = $token;
        }elseif($providerName == "TwitterProvider") {
            $user->twitter_token = $token;
        }else{
            $user->google_token = $token;
            }
        $user->save();
        }
        if (!$user) {
            $user = User::create([
                'email' => $providerUser->getEmail(),
                'name' => $providerUser->getName(),
                'avatar' => $providerUser->getAvatar(),
            ]);
        }
        $account->user()->associate($user);
        $account->save();
        return $user;
    }
}

The only problem with that is it never runs the check for $providerName == "facebookprovider" etc and update the token for that user. Is there any particular reason for why this is happening?

4
  • With $user = User::whereEmail($providerUser->getEmail())->first();, you already get one object. Why, in the next line, do you reuse first()? Commented Aug 10, 2017 at 13:33
  • why use this if($user->first()) it is better if you use if(!empty($user)) Commented Aug 10, 2017 at 13:34
  • I tried if(!empty($user)) and it didn't work Commented Aug 10, 2017 at 13:36
  • try to dump your $user before if statement Commented Aug 10, 2017 at 13:37

1 Answer 1

0

Found on the documentation:

If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single StdClass object

You get stdClass object when you called first() the first time. The second one will probably never be true, because this class has not this method.

It could work if you change if ($user->first()) by if ($user).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.