Adam nick Adam nick - 2 months ago 8
PHP Question

laravel is showing pivot table data also when using eagerloading

I am using eagerloading to fetch many to many relationship data. Here is my code

$sport = Sport::with([

'sport_levels' => function($q) use ($sportId, $schoolId){
$q->select('levels-sports.id', 'sport_id', 'name')->where('sport_id', $sportId)->
where('school_id', $schoolId)->get();
}
])
->select('id', 'season_id', 'id as sport_id', 'name as sport_name', 'photo as sport_photo', 'record as sport_record')
->where('school_id', $schoolId)->where('id', $sportId)->get();


and the result is

[{"id":1,"season_id":2,"sport_id":1,"sport_name":"Football","sport_photo":"2479.png","sport_record":"Ggqfx","sport_levels":[{"id":1,"sport_id":1,"name":"Expert","pivot":{"sport_id":1,"level_id":1}}]}]


which is also showing the pivot table, how I can hide this?

Answer

You can add pivot data by adding that to the list of hidden attributes of your model:

class SportLevel extends Model {
  protected $hidden = [
    'pivot'
  ];
}
Comments