问题描述
我不确定这是否是真正引起我问题的原因,但也许有人会知道.当我使用Laravel Socialite并前往时:
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:
传递给Illuminate \ Auth \ SessionGuard :: login()的参数1必须实现Illuminate \ Contracts \ Auth \ Authenticatable接口,Illuminate \ Database \ Eloquent \ Builder的实例已给出
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;
我这样登录该用户:
Auth::login($authUser, true);
有人知道为什么吗?我正在使用laravel 5.2
Does anyone know why? I'm using laravel 5.2
推荐答案
错误消息实际上是自我解释的.当您执行User::where('provider_id', $social_user->id)
时,最终会得到实现Illuminate\Database\Eloquent\Builder
的 builder对象.您可以调用->get()
以获得结果集合(在您的情况下实现Illuminate\Contracts\Auth\Authenticatable
的对象的集合,因此您可以对其进行迭代),或者可以这样做->first()
(实现Illuminate\Contracts\Auth\Authenticatable
的一个对象)获得首次匹配.您可以在口才文档中了解更多信息.
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.
要点是,直到您致电 ->get()
或->first()
,您将使用构建器对象.实际上也有->find()
方法,该方法用于按pk
检索记录,您不能使用它按约束条件(where)搜索记录,但是它还会返回模型对象.
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.
这篇关于Laravel社交名流$ user-> getId()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!