Laravel 4.2 Eloquent ORM 我的代码有什么问题

What wrong in my code with Laravel 4.2 Eloquent ORM

当以下执行时:

$user = User::where('email','=',$email)->take(1)->get();
Auth::login($user);

我收到错误:

Argument 1 passed to Illuminate\Auth\Guard::login() must implement interface Illuminate\Auth\UserInterface, instance of Illuminate\Database\Eloquent\Collection given ...

我试过将其更改为:

$user = User::where('email','=',$email)->take(1)->get();
$userid = $user->id;
$user=User::find($userid);
Auth::login($user);

但是我得到了错误:

Undefined property: Illuminate\Database\Eloquent\Collection::$id

当你使用 get() 时,它 returns 用户集合意味着你可能有多个记录,虽然你已经使用 take(1) 但那个数字可能不同所以它总是 returns 集合,所以你不能直接访问对象的 属性。

您可以使用 first() 获取单个用户对象。

试试这个

$user = User::where('email','=',$email)->first();
Auth::login($user);

编辑

你可以在这里使用firstOrFail()代替first(),就好像你没有通过错误得到指定的用户firstOrFail()