简体   繁体   中英

Laravel User Eloquent model returning null when record exists

Hair-pulling time.

I have implemented a callback for Laravel Socialite. It's running User::where against the Twitter user ID, but is always returning null despite the fact that there is a record in the database that matches.

Therefore it always tries to create a new user, leading to an error of this kind:

QueryException in Connection.php line 673: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry...

Here's the callback function. $twitterUser is the incoming user record from Socialite. I have tried explicitly using \\App\\User\\ in the function, but to no avail.

private function findOrCreateUser( $twitterUser )
{
  $user = User::where( 'twitter_id', $twitterUser->id )->first();

  if ($user)
  {
    return $user;
  }

  return User::create([
    'name'        => $twitterUser->name,
    'handle'      => $twitterUser->nickname,
    'twitter_id'  => $twitterUser->id,
    'avatar'      => $twitterUser->avatar_original
  ]);
}

If I run the code elsewhere in the app, the user shows up fine, and if I try php artisan tinker followed by \\App\\User::where('twitter_id', 123456789)->first() I get a result:

=> App\User {#663
 id: 3,
 name: "Steve Jones",
 handle: "SteveJonesGtr",
 twitter_id: 123456789,
 avatar: "http://pbs.twimg.com/profile_images/whatever/bC0RLl-3.jpeg",
 created_at: "2016-04-20 11:41:39",
 updated_at: "2016-04-20 11:41:39",

}

EDIT: If I change the where clause to this, it works:

$user = User::where( 'handle', $twitterUser->nickname )->first();

But I can't see why it won't return a result for this:

$user = User::where( 'twitter_id', $twitterUser->id )->first();

Any ideas?

you are searching for 12345678 not 123456789 thats your problem. your missing the 9 at the end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM