错误:在文件 Http\Controllers\TaskController.php 中调用成员函数 tasks() 为空

问题描述 投票:0回答:1

我已经配置了

JWT
laravel
postman
,我有两个表
users
tasks
,它们之间的关系
hasMany
BelongsTo
在这里:

task.php

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

User.php

public function tasks()
     {
         return $this->hasMany(Task::class);
     }

和一个返回

tasks

列表的函数

Taskcontroller.php

public function index()
{
     $tasks = $this->user->tasks()->get(['title', 'description'])->toArray();

     return $tasks;
}

但它给了我错误:

Error: Call to a member function tasks() on null in file C:\wamp64\www\jwtestb\app\Http\Controllers\TaskController.php on line 30
laravel jwt relationship
1个回答
0
投票

$this->user
不存在。如果您想获得经过身份验证的用户,您可以使用
Auth
门面或
Request
对象。

use Illuminate\Support\Facades\Auth; // or use Auth;

public function index()
{
     $tasks = Auth::user()->tasks()->get(['title', 'description'])->toArray();

     return $tasks;
}
public function index()
{
     $tasks = auth()->user()->tasks()->get(['title', 'description'])->toArray();

     return $tasks;
}
public function index()
{
     $tasks = request()->user()->tasks()->get(['title', 'description'])->toArray();

     return $tasks;
}
use Illuminate\Http\Request;

public function index(Request $request)
{
     $tasks = $request->user()->tasks()->get(['title', 'description'])->toArray();

     return $tasks;
}
© www.soinside.com 2019 - 2024. All rights reserved.