title: How to get data with pivot data attached?
body: <p>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.</p>
  
  <p>This is a sample of the database model, with a relation N:M.</p>
  
  <p><a href="https://i.stack.imgur.com/yIy9x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yIy9x.png" alt="database model"></a></p>
  
  <p>In my List model, I added this method:</p>
  
  <pre class="lang-php prettyprint-override"><code>public function tracks()
  {
     return $this-&gt;belongsToMany(Track::class, 'List_Tracks', 'id_list', 'id_track');
  }
  </code></pre>
  
  <p>So, in my ListController, I'm doing the following:</p>
  
  <pre class="lang-php prettyprint-override"><code>$list = List::find($id);
  $list-&gt;tracks_list = $list-&gt;tracks-&gt;pluck('track_id');
  return $list;
  </code></pre>
  
  <p>And what I get is as many objects as tracks I have in a same list, for example:</p>
  
  <pre><code>[
  {
   "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
   }
  }
  ]
  </code></pre>
  
  <p>But what I want to get is:</p>
  
  <pre><code>{
   "id_list": 1,
   "name": "The Best of The Beatles",
   "tracks_list": [
    1,
    2
  ]
  }
  </code></pre>
  
  <p>I think the things I've tried are much more complex than the proper solution.</p>
  
  <p>How would you get the data in this way?</p>
  
  <p>Thanks in advance.</p>