我已经配置了
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
$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;
}