Laravel: JSON and Dashboard

Sorry for the obscure name, but I could not come up with a descriptive one.

I have the following 3 tables: - games - platforms - games_platforms

And I have 2 Models in Laravel for platform and game.

public function games() { return $this->belongsToMany('App\Game', 'games_platforms')->withPivot('release_date'); } public function platforms() { return $this->belongsToMany('App\Platform', 'games_platforms')->withPivot('release_date'); } 

Now it works like a charm, I get a JSON string with all the information in three tables, for example.

 [{ "id": 1, "name": "Borderlands", "short_description": "", "created_at": null, "updated_at": null, "platforms": [{ "id": 4, "name": "PC", "pivot": { "game_id": 1, "platform_id": 4, "release_date": "2016-03-03" } }] }] 

Now my problem is as follows. I do not want to show all the "summary" information, just "release_date", for example:

 "platforms": [{ "id": 4, "name": "PC", "release_date": "2016-03-03" 

Is there an easy way to do this in Laravel? As far as I can see right now, looking at other posts, I need to either write a function that turns json into an array, and then I can organize it. Or I can write my own query instead of letting Laravel do all of this.

Hope you guys can help me with this problem. Thanks!

+5
source share
2 answers

I would modify the data returned from the request using the methods of the collection class:

 //replace Game::all() with your actual query return Game::all()->each(function($game){ $game->platforms->map(function($platform){ $platform->release_date = $platform->pivot->release_date; unset($platform->pivot); return $platform; }); }); 
+4
source

I know that this has already been answered, but I believe that the correct answer would be to add everything you want to hide to your hidden attribute on the model.

 <?php class Games extends Eloquent { protected $hidden = ['pivot.game_id', 'pivot.platform_id']; } 

I'm not sure what your keys are, because they are different in your two examples. See: https://github.com/laravel/framework/issues/745

+1
source

All Articles