Laravel using where clause on a withCount method

Eloquent has one less-known function called withCount(): it helps to get the amount of related records inside of the main object. It also works with two layers deep, inside of hasManyThrough relations

Whenever you require to count rows of relation model then we will use withcount(). So that can help us. you can see bellow example. We will count number of articles for each categories. you can see bellow example.

Simple Count Example

$categories = Category::withCount('articles')->get();
//articles_count

Multiple Counts Example

$categories = Category::withCount(['articles','products'])->get();
//articles_count, products_count

Count With Condition Example

$categories = Category::withCount(['articles' => function ($query) {
            $query->where('status', 1);
        }])->get();
//articles_count

I hope it can help you...

Leave a comment

your email address will not be published. required fields are marked *

Name *
Email *
Phone