title: Retrieve related models using hasManyThrough on a pivot table - Laravel 5.7
body: <p>I'm trying to retrieve related models of the same type on from a pivot table.</p>
  
  <p>I have 2 models, <code>App\Models\User</code> and <code>App\Models\Group</code> and a pivot model <code>App\Pivots\GroupUser</code></p>
  
  <p>My tables are have the following structure</p>
  
  <p>users</p>
  
  <ul>
  <li>id</li>
  </ul>
  
  <p>groups</p>
  
  <ul>
  <li>id</li>
  </ul>
  
  <p>group_user</p>
  
  <ul>
  <li>id</li>
  <li>user_id</li>
  <li>group_id</li>
  </ul>
  
  <p>I have currently defined relationships as</p>
  
  <p>In app/Models/User.php</p>
  
  <pre><code>public function groups()
  {
      return $this-&gt;belongsToMany(Group::class)-&gt;using(GroupUser::class);
  }
  </code></pre>
  
  <p>In app/Models/Group.php</p>
  
  <pre><code>public function users()
  {
      return $this-&gt;belongsToMany(User::class)-&gt;using(GroupUser::class);
  }
  </code></pre>
  
  <p>In app/Pivots/GroupUser.php</p>
  
  <pre><code>public function user()
  {
      return $this-&gt;belongsTo(User::class);
  }
  
  public function group()
  {
      return $this-&gt;belongsTo(Group::class);
  }
  </code></pre>
  
  <p>I'm trying to define a relationship in my <code>User</code> class to access all other users that are related by being in the same group. Calling it <code>friends</code>. So far I've tried this:</p>
  
  <p>app/Models/User.php</p>
  
  <pre><code>public function friends()
  {
      return $this-&gt;hasManyThrough(
          User::class,
          GroupUser::class,
          'user_id',
          'id'
      );
  }
  </code></pre>
  
  <p>But it just ends up returning a collection with only the user I called the relationship from. (same as running <code>collect($this);</code></p>
  
  <p>I have a solution that does work but is not ideal.</p>
  
  <p>app/Models/User.php</p>
  
  <pre><code>public function friends()
  {
      $friends = collect();
      foreach($this-&gt;groups as $group) {
          foreach($group-&gt;users as $user) {
              if($friends-&gt;where('id', $user-&gt;id)-&gt;count() === 0) {
                  $friends-&gt;push($user);
              }
          }
      }
  
      return $friends;
  }
  </code></pre>
  
  <p>Is there a way I can accomplish this using <code>hasManyThrough</code> or some other Eloquent function?</p>
  
  <p>Thanks.</p>