Laravel - Relationships issue
<p>I have 3 models: </p>

<pre><code>class Site extends Model
{
    public function users()
    {
        return $this-&gt;belongsToMany('App\Models\User');
    }
    public function stats()
    {
        return $this-&gt;hasMany('App\Models\Stat');
    }
}

class User extends Model
{
    public function sites()
    {
        return $this-&gt;belongsToMany('App\Models\Site');
    }
    public function stats()
    {
        return $this-&gt;belongsToMany('App\Models\Stat');
    }
}

class Stat extends Model
{

    public function users()
    {
        return $this-&gt;belongsToMany('App\Models\User');
    }
    public function sites()
    {
        return $this-&gt;belongsTo('App\Models\Site');
    }
}
</code></pre>

<p>So there are : </p>

<ul>
<li>a many to many relation between sites and users</li>
<li>a many to many relation between users and stats</li>
<li>a one to many relation between site and stats</li>
</ul>

<p>A site have a list of stats and from this list, an user can have some stats.</p>

<p><a href="https://i.stack.imgur.com/pzFNr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pzFNr.png" alt="enter image description here"></a></p>

<p>I'm trying to get all sites and foreach site, count of stats for the connected user.</p>

<p>For the moment i tried :</p>

<pre><code>//repository
function getAll($user_id = 0)
{

    $with = [];

    $with['users'] = function ($query) use ($user_id) {
        $query-&gt;where('id', '=', $user_id);
    };
    return Site::with($with)-&gt;orderBy('name')-&gt;get();
}
//controller
$sites = getAll($user_id);

//view
foreach($sites as $site){
  $count_stats = $site-&gt;users-&gt;first()-&gt;stats-&gt;where('site_id',$site-&gt;id)-&gt;count();
}
</code></pre>

<p>It works but it is not very elegant, it does a lot of sql requests and the page is slower.</p>

<p><strong>Do you have a better solution ?</strong></p>