title: Laravel eager load through pivot?
body: <p>I'm trying to eager load some data through an id in a pivot table.</p>
  
  <p>Right now I've just done it manually but wondering if there is a way to do this directly through eloquent with a relation?</p>
  
  <pre><code>$ids = $tournament-&gt;matches
                    -&gt;pluck('users')
                    -&gt;flatten()
                    -&gt;pluck('pivot')
                    -&gt;pluck('team_id')
                    -&gt;unique();
  
  $teams = \App\Models\Team::whereIn('id', $ids)-&gt;get()-&gt;keyBy('id');
  
  $tournament-&gt;matches-&gt;each(function ($match) use ($teams) {
      $match-&gt;users-&gt;each(function ($user) use ($teams) {
          $user-&gt;team = @$teams[$user-&gt;pivot-&gt;team_id] ?: null;
      });
  });
  </code></pre>