title: Laravel eloquent relationship and pivot tables
body: <p>Im experimenting with an Laravel application where I have users and teams. The tables looks a little bit like this (simplified):</p>
  
  <p><strong>users</strong></p>
  
  <ul>
  <li>id* </li>
  <li>...</li>
  </ul>
  
  <p><strong>teams</strong></p>
  
  <ul>
  <li>id* </li>
  <li>... </li>
  </ul>
  
  <p><strong>team_user</strong></p>
  
  <ul>
  <li>team_id*</li>
  <li>user_id*</li>
  <li>isLeader</li>
  <li>confirmed</li>
  </ul>
  
  <p>As you can see, a user can be part of a number of teams, and *he can also be appointed leader of a given team. A team can have multiple leaders.</p>
  
  <p>The user model has the following relationships:</p>
  
  <pre><code>// Returns all the teams connected to the user and where the confirmed timestamp is set
  public function teams()
  {
      return $this-&gt;belongsToMany(Team::class)-&gt;wherePivot('confirmed', '!=', null);
  }
  // Returns all the teams where the user is appointed team leader
  public function teamleaderTeams()
  {
      return $this-&gt;belongsToMany(Team::class)-&gt;wherePivot('isLeader', '=', 1);
  }
  </code></pre>
  
  <p>The team has:</p>
  
  <pre><code>public function confirmedUsers()
  {
      return $this-&gt;belongsToMany(User::class)-&gt;where('confirmed', '!=', null);
  }
  </code></pre>
  
  <p>I need something that returns all the users that the user is team leader for. So if you are not a team leader the result would off course be empty, but if you are it should return all the users from all the teams where you are appointed leader.</p>
  
  <p>Ive tried asking around, and have gotten some suggestions, but not really arrived at a solution.
  I do kindof understand what I want (I think). Sooo... since you can tell which teams a user is team leader for through the teamleaderTeams() relation, I can loop through each and then ask to get all the confirmed users through the confirmedUsers() relation. But I've only managed to accomplish this in the controller and it just seems messy. </p>
  
  <p>I.e. this only crashes the browser (it seems to be in an infinite loop or something, and I dont really understand why). </p>
  
  <pre><code>public function getLeaderForAttribute()
  {
          $users = collect();
          foreach($this-&gt;teamleaderTeams as $team)
          {
              foreach ($team-&gt;confirmedUsers as $user) {
                  $users-&gt;add($user);
              }
          }
          return $users-&gt;unique('id');
  }
  </code></pre>
  
  <p>Anyway, anyone got a nice solution for a teamleaderUsers() relation (not really a good name for it), that returns all the users from all the teams that a given user is team leader for (thats a mouth full)? </p>