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