-3

I am using $hidden and $appends to hide pivot keyword from json array and pull the objects into main array. In the game model I added below script to do functionality as I said above

    protected $hidden = ['pivot'];
    protected $appends = ['user_id','highscore', 'level'];

    public function getUserIdAttribute()
    {
        return $this->pivot->user_id;
    }

    public function getHighScoreAttribute()
    {
        return $this->pivot->highscore;
    }

    public function getLevelAttribute()
    {
        return $this->pivot->level;
    }

Now the problem is that I want to fetch all games and I know it is so simple I just added into controller below script

$Games = Game::all();
return new GameResource($Games); /* GameResource is for API */

But the this one is return following error after adding above script into model.

ErrorException: Trying to get property user_id of non-object 

Anyone can guide me please how to manage both of functionality because I need both of. I would appreciate if someone kindly guide.

After @emix Comment

@emix it is not duplicated because the reference is about core php and I am using laravel. Off course laravel is built with php but still there is complicated structure so I think this one is not same as you refered

Script Lover
  • 331
  • 2
  • 6
  • 15
  • Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Mike Doe Nov 07 '18 at 12:23
  • @emix it is not duplicated because the reference is about core php and I am using laravel. Off course laravel is built with php but still there is complicated structure so I think this one is not same as you refered – Script Lover Nov 07 '18 at 12:25
  • 1
    Well obviously your `GameResource` class tries to access the `pivot` property which is null. Mentioned Wiki explains well how to handle such situations. – Mike Doe Nov 07 '18 at 12:26
  • @emix above one is so useful can you kindly help me more please – Script Lover Nov 07 '18 at 12:28
  • @ScriptLover can you post your Game model user relationship? – Adam Rodriguez Nov 07 '18 at 15:12

1 Answers1

1

The pivot is only available when you're fetching the models through the many-to-many relationship (BelongsToMany). The pivot represents the fields on the pivot table (eg. games_users) and thus fields that exist for that specific relationship.

When you're just pulling directly from the Game model (aka. games table), you have no relationship or pivot table to pull data from.

Devon Bessemer
  • 34,461
  • 9
  • 69
  • 95