Suppose we have a laravel application and now we want to count the number of comments on every post. How we can do it? We can do it using query builder using count helper. But in this example will do it using an eloquent query. Sometimes we want to count the number of related models for a given relationship without actually loading the models. in this case, laravel provides withCount() helper to do that.

In this example, I will show you how to use withcount in laravel. In this example, we will count total number of comments for each post. So let's see the example code of withcount laravel 9:

laravel-9-withcount-example

Laravel withcount example for the total number of comments of each post:

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')->get();
    }
}

 

Now see the output:

[
    {
        "id": 1,
        "user_id": 1,
        "title": "Maxime non architecto quia in corporis iusto odio beatae.",
        "is_published": 1,
        "created_at": "2023-01-15T04:59:18.000000Z",
        "updated_at": "2023-01-15T04:59:18.000000Z",
        "comments_count": 1
    }
]

 

Laravel withcount alias example for the total number of comments of each post:

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 as total_post')->get();
    }
}

 

Now see the output:

[
    {
        "id": 1,
        "user_id": 1,
        "title": "Maxime non architecto quia in corporis iusto odio beatae.",
        "is_published": 1,
        "created_at": "2023-01-15T04:59:18.000000Z",
        "updated_at": "2023-01-15T04:59:18.000000Z",
        "total_post": 1
    }
]

 

Read also: Laravel WhereHasMorph Query Example

 

Conclusion

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