如何获取与登录用户 ID 匹配的任务?

How to get tasks that match logged in user id?

在控制器中:

$user = user()->id;
$tasks = task::with('user')->where('tasks.user_id', '=', '$user')->get();

任务模型:

public function user()
{
    return $this->belongsTo(User::class, 'user_id', 'id');
}

用户模型:

public function Tasks()
{
    /**
     * The relationship to the user's tasks.
     *
     * @return HasMany
     */
    return $this->hasMany(Task::class, 'user_id', 'id');
}

这是错误:尝试获取 属性 'user_id' 的非对象

Auth::user()->id;Auth::id();获取登录用户的身份;您可以使用。详细信息可以在这里查看:https://laravel.com/docs/8.x/authentication#retrieving-the-authenticated-user

$user = auth()->user()->id; //This line of code will give Authenticated user id.
$tasks = task::with('user')->where('tasks.user_id', '=', $user)->get(); //Remove single quate from $user variable

$user = \Auth::user()->id; 
$tasks = task::with('user')->where('tasks.user_id', '=', $user)->get();

希望这会有所帮助。

您可以简单地调用

$tasks = Auth::user()->tasks;

$tasks 包含属于当前用户的任务