Laravel 5.3 withCount() nested relation

You can only do a withCount() on a defined relation of the model.

However, a relationship can be hasManyThrough which would achieve what you are after.

class Tutorial extends Model
{
    function chapters()
    {
        return $this->hasMany('App\Chapter');
    }

    function videos()
    {
        return $this->hasManyThrough('App\Video', 'App\Chapter');
    }
}

And then you can do:

Tutorial::withCount(['chapters', 'videos'])

Docs:

Leave a Comment