如何使用 /user api 身份验证来使用 Laravel 资源
How to user Laravel resource with /user api of Authentication
我正在使用 Laravel 和 Vue 使用 Axios 和 Passport 构建一个项目。
我的身份验证正在运行并生成令牌并保存在我的本地存储中以检查登录。
我也在使用
获取数据
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());
error: syntax error, unexpected 'collection' (T_STRING), expecting variable (T_VARIABLE) or '$'
return UserResource::collection($request->user()-get());
error: Trying to get property 'typeName' of non-object
那我做错了什么?感谢您抽出时间,如果需要更多详细信息,请告诉我
您可以使用 Eager loading
获得类似甚至更好的结果。 source
样本:
Route::get('me', function(Request $request) {
$request->user()->load('types');
});
我正在使用 Laravel 和 Vue 使用 Axios 和 Passport 构建一个项目。
我的身份验证正在运行并生成令牌并保存在我的本地存储中以检查登录。
我也在使用
获取数据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());
error: syntax error, unexpected 'collection' (T_STRING), expecting variable (T_VARIABLE) or '$'
return UserResource::collection($request->user()-get());
error: Trying to get property 'typeName' of non-object
那我做错了什么?感谢您抽出时间,如果需要更多详细信息,请告诉我
您可以使用 Eager loading
获得类似甚至更好的结果。 source
样本:
Route::get('me', function(Request $request) {
$request->user()->load('types');
});