Laravel socialite $user->getId()?

99封情书 提交于 2019-12-23 19:03:43

问题


I'm not sure if this is what is really causing my issue, but perhaps someone will know. When I use Laravel Socialite and go:

$social_user = Socialite::driver($provider)->user();

Then somewhere else in my code is do this:

if ($authUser = User::where('provider_id', $social_user->id)) 
        return $authUser;

For some crazy reason I get an error like this:

Argument 1 passed to Illuminate\Auth\SessionGuard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, instance of Illuminate\Database\Eloquent\Builder given

However if I do this I don't get an error:

if($authUser = User::where('email', $social_user->email)->first())
        return $authUser;

I log this user in like this:

Auth::login($authUser, true);

Does anyone know why? I'm using laravel 5.2


回答1:


The error message is actually self explained. When you do User::where('provider_id', $social_user->id) you end up with builder object that implements Illuminate\Database\Eloquent\Builder. You can call ->get() on it to get the collection of results (a collection of objects that implements Illuminate\Contracts\Auth\Authenticatable in your case, so you can iterate over them), or as you did, you can get the first match with ->first() (one object that implement Illuminate\Contracts\Auth\Authenticatable). You can read more in the Eloquent documentation.

The main point is that until you call ->get() or ->first() you are working with builder object. There is actually ->find() method also, that is used to retrieve record by pk, you cannot use it to search for records by constraints (where), but it also returns model object.



来源:https://stackoverflow.com/questions/37247380/laravel-socialite-user-getid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!