php - 拉拉维尔 5.2 : Fetch records against logged in user id

标签 php laravel laravel-5

我正在 Controller 中获取记录:

$tasks = Task::where('user_id', '=', Auth::user()->id);

return view('todo',compact('tasks'));

但它返回 null。

并且 Auth::user()->id 返回 2 没问题。

我错过了什么吗?

最佳答案

您需要实际检索记录。您拥有的是 \Illuminate\Database\Eloquent\Builder 的实例,但不是与查询关联的实际记录。

要告诉 Eloquent 获取数据,您需要使用 get()

喜欢:

$tasks = Task::where('user_id', '=', Auth::user()->id)->get();

顺便说一句,您可以将查询简化为:

$tasks = Task::where('user_id', Auth::user()->id)->get();

此外,在您的 User 模型上,您可以执行以下操作:

public function tasks()
{
    return $this->hasMany(Task::class) // make sure you use the full namespace here or use at the top of User.php
}

然后你可以简单地做:

$tasks = auth()->user()->tasks;

这是 Eloquent 中解释的关系 in the docs .

关于php - 拉拉维尔 5.2 : Fetch records against logged in user id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37084635/

相关文章:

php - Laravel Composer错误未捕获的ReflectionException:Container.php:738中不存在类日志

php - 拉维尔 5.5 : array_combine(): Both parameters should have an equal number of elements

php - 如何在数组中回显数组?

php - 如何在 php 中获取所有具有特定文件夹名称的子目录?

PHP while 循环修改最后一次迭代

php - Laravel Eloquent wherePivot 方法返回未找到列 'pivot'

php - Laravel 如何使用 auth :user() 返回选定的列

php - "->"在 PHP 中是什么意思/指的是什么?

php - 从作业处理程序调用 Laravel Controller 操作,使用依赖注入(inject)

php - Laravel 5 找不到 css 文件