It is a bit difficult to use withcout with a nested relationship in laravel. We can not use withcount with nested relationship like withCount(['comments.replies']) in eloquent query. Then how we can use laravel withcount nested relationship? In this tutorial, I will show you two example of how to use withcount with nested relationship in laravel application.

One example will be the normal way and another example will be using hasManyThrough relationship. Let's try how we can use withCount with the nested relationships in laravel.

laravel-withcount-nested-relationship

Now let's see the update the Post model like:

app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Post extends Model
{
    use HasFactory;

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

 

Now let's see the update the Comment model like:

app/Models/Comment.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use HasFactory;

    public function replies()
    {
        return $this->hasMany(Reply::class);
    }

    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

 

Now let's see the update on the Reply model like:

app/Models/Reply.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Reply extends Model
{
    use HasFactory;

    public function comment()
    {
        return $this->belongsTo(Comment::class);
    }
}

 

Now see the example code of laravel withcount nested relationship

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Post::withCount('comments')
                    ->with(['comments' => function($query){
                        $query->withCount('replies');
                    }])
                    ->get();
    }
}

 

Now let's see the output of laravel withcount nested relationship query:

[
    {
        "id": 1,
        "user_id": 1,
        "title": "Eius quia id consequatur mollitia dolor totam debitis facere. Reiciendis non magni sed. Itaque ducimus labore nemo ipsa unde voluptas. In repellendus quo expedita adipisci qui aut. Labore molestias est voluptatem.",
        "is_published": 1,
        "created_at": "2023-01-22T12:22:48.000000Z",
        "updated_at": "2023-01-22T12:22:48.000000Z",
        "comments_count": 2,
        "comments": [
                {
                    "id": 1,
                    "post_id": 1,
                    "user_id": 1,
                    "comment": "Magni eveniet itaque ratione atque.",
                    "is_approved": 0,
                    "created_at": "2023-01-22T12:22:48.000000Z",
                    "updated_at": "2023-01-22T12:22:48.000000Z",
                    "replies_count": 3
                },
                {
                    "id": 2,
                    "post_id": 1,
                    "user_id": 1,
                    "comment": "Fugiat recusandae ipsam veniam unde necessitatibus ratione facilis eum.",
                    "is_approved": 0,
                    "created_at": "2023-01-22T12:22:48.000000Z",
                    "updated_at": "2023-01-22T12:22:48.000000Z",
                    "replies_count": 2
                }
            ]
    },
    {
        "id": 2,
        "user_id": 2,
        "title": "Similique sunt ex placeat quae cupiditate. Sapiente ullam omnis recusandae ipsa sed ut deleniti. Mollitia quis magni voluptatem qui unde.",
        "is_published": 1,
        "created_at": "2023-01-22T12:22:48.000000Z",
        "updated_at": "2023-01-22T12:22:48.000000Z",
        "comments_count": 1,
        "comments": [
            {
                "id": 3,
                "post_id": 2,
                "user_id": 2,
                "comment": "Quibusdam quo reiciendis incidunt pariatur aut et.",
                "is_approved": 0,
                "created_at": "2023-01-22T12:22:48.000000Z",
                "updated_at": "2023-01-22T12:22:48.000000Z",
                "replies_count": 1
            }
        ]
    }
]

 

Another way of laravel withcount nested relationship

Now I will show you another way of solving laravel withcount nested relationship. To solve this how to use withcount with nested relationship, I will use hasManyThrough relationship. If you do not know hasManyThrough, than you can follow this tutorial:

 

Read also: Laravel 9 Has Many Through Eloquent Relationship Tutorial

 

Now update the Post model with this hasManyThrough relationship like that:

App\Models\Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Post extends Model
{
    use HasFactory;

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    public function replies()
    {
        return $this->hasManyThrough(Reply::class,Comment::class);
    }
}

 

Now see the example code of withcount nested relationship laravel:

app/Http/Controllers/TutorialController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;

class TutorialController extends Controller
{   
    public function index()
    {   
        return Post::withCount(['comments', 'replies'])->get();
    }
}

 

Now see the output:

[
    {
        "id": 1,
        "user_id": 1,
        "title": "Eius quia id consequatur mollitia dolor totam debitis facere. Reiciendis non magni sed. Itaque ducimus labore nemo ipsa unde voluptas. In repellendus quo expedita adipisci qui aut. Labore molestias est voluptatem.",
        "is_published": 1,
        "created_at": "2023-01-22T12:22:48.000000Z",
        "updated_at": "2023-01-22T12:22:48.000000Z",
        "comments_count": 2,
        "replies_count": 5
    },
    {
        "id": 2,
        "user_id": 2,
        "title": "Similique sunt ex placeat quae cupiditate. Sapiente ullam omnis recusandae ipsa sed ut deleniti. Mollitia quis magni voluptatem qui unde.",
        "is_published": 1,
        "created_at": "2023-01-22T12:22:48.000000Z",
        "updated_at": "2023-01-22T12:22:48.000000Z",
        "comments_count": 1,
        "replies_count": 1
    }
]

 

Read also: Laravel 9 Multiple WithCount Query Example

 

Conclusion

In this laravel withcount nested relationship tutorial,  I have tried my best to let you know the clear concept of how to use withcount with nested relationship example. Hope now after completing this tutorial, you will know laravel nested relationship with withcount and you will be able to solve your problem about withcount nested relationship laravel.