1

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

4
  • 1
    the types relationship can return null, 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 Commented Oct 15, 2019 at 21:42
  • hi @lagbox, relationship does exists and it's not returning null as all the data has types column filled with factories. Commented Oct 15, 2019 at 21:58
  • Hi @DinoNumić, thanks for your reply. If you check my question I have tried that but it is returning error too Commented Oct 15, 2019 at 22:02
  • @Zee I have removed my comment as I was not completely sure and I had to check it first. I have checked your question but you are still calling collection on UserResource. You can't do it if you a single model instance. Commented Oct 15, 2019 at 22:37

1 Answer 1

1

You can achieve similar, if not better results using Eager loading. source

Sample:

Route::get('me', function(Request $request) {
    $request->user()->load('types');
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.