I'm trying to get the data from my Lists table and include an array with the ID's of the tracks in that list.
This is a sample of the database model, with a relation N:M.
In my List model, I added this method:
public function tracks()
{
return $this->belongsToMany(Track::class, 'List_Tracks', 'id_list', 'id_track');
}
So, in my ListController, I'm doing the following:
$list = List::find($id);
$list->tracks_list = $list->tracks->pluck('track_id');
return $list;
And what I get is as many objects as tracks I have in a same list, for example:
[
{
"id_track": 1,
"name": "Yesterday",
"tracks_list": [
1,
2
]
"pivot": {
"id_list": 1,
"id_track": 1
}
},
{
"id_track": 2,
"name": "Lucy in the sky with diamonds",
"pivot": {
"id_list": 1,
"id_track": 2
}
}
]
But what I want to get is:
{
"id_list": 1,
"name": "The Best of The Beatles",
"tracks_list": [
1,
2
]
}
I think the things I've tried are much more complex than the proper solution.
How would you get the data in this way?
Thanks in advance.