I am building a project with Laravel and Vue using Axios and Passport.
My authentication is working and generating token and saving in my local storage to check for login.
I am also getting the data using
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
However, my user also has some relationship which I have described in my model like
public function types()
{
return $this->belongsTo(types::class, 'type_id');
}
and my user resource looks like this
public function toArray($request)
{
$array = parent::toArray($request);
$array['group'] = $this->groups;
$array['type'] = $this->types->typeName;
return $array;
}
So when user login I am trying to get user data using auth:api however I want a relationship to come with it.
I tried
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
So what am I doing wrong? thanks for your time and if need more details please let me know
typesrelationship can returnnull, you will need to check to make sure the relationship actually exists ... and you should probably work on the naming of relationships to make it more obvious when something returns 1 or many (singular or plural), will make things easier