我正在使用Axios和Passport与Laravel和Vue建立一个项目。
我的身份验证正在起作用,并且正在生成令牌并将其保存在本地存储中以检查是否登录。
我也正在使用
获取数据Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
但是,我的用户还具有我在模型中描述的某些关系,例如
public function types()
{
return $this->belongsTo(types::class, 'type_id');
}
我的用户资源看起来像这样
public function toArray($request)
{
$array = parent::toArray($request);
$array['group'] = $this->groups;
$array['type'] = $this->types->typeName;
return $array;
}
因此,当用户登录时,我尝试使用auth:api获取用户数据,但是我希望与之建立联系。
我尝试了
Route::middleware('auth:api')->get('/user', function (Request $request) {
return UserResource::collection($request->user());
});
and get error
> Call to undefined method App\User::mapInto()
I also tried
```php
return new UserResource::collection($request->user());
错误:语法错误,意外的“集合”(T_STRING),预期变量(T_VARIABLE)或“ $”
return UserResource::collection($request->user()-get());
错误:尝试获取非对象的属性'typeName'
那我做错了什么?感谢您的宝贵时间,如果需要更多详细信息,请告诉我
答案 0 :(得分:1)
使用Eager loading
可以获得类似甚至更好的结果。 source
示例:
Route::get('me', function(Request $request) {
$request->user()->load('types');
});