Laravel Eloquent withCount() and withCount() with where condition

 

In this blog, We will learn about using withCount() function. This simple function helps in getting the number of records in the relation containing hasMany() relation with the current model. I will give you simple examples to explain withCount() function. 


We will create two models Category and Product containing records.


Let's start with examples,


Category Model


<?php

  

namespace App\Models;

  

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

  

class Category extends Model

{

    use HasFactory;

   protected $fillable = [

        'id', 'name'

    ];

    /**

     * Get the comments for the blog post.

     */

    public function products()

    {

        return $this->hasMany(Product::class);

    }

}


Product Model


<?php

  

namespace App\Models;

 

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

  

class Product extends Model

{

    use HasFactory;

  

    protected $fillable = [

        'name', 'price', 'is_active'

    ];

}


Using withCount() 


<?php

  

namespace App\Http\Controllers;

  

use App\Models\Category;

  

class DataCountController extends Controller

{

    /**

     * Write code on Method

     *

     * @return response()

     */

    public function index()

    {

        $categories = Category::select("id", "name")

                        ->withCount('products')

                        ->get()

                        ->toArray();

 

        dd($categories);

    }

}



Output:


Array

(

    [0] => Array

        (

            [id] => 1

            [name] => Mobile

            [products_count] => 3

        )

    [1] => Array

        (

            [id] => 2

            [name] => Laptop

            [products_count] => 2

        )

)



Using withCount() with Where Condition Example:


<?php

  

namespace App\Http\Controllers;

  

use App\Models\Category;

  

class DataCountController extends Controller

{

    /**

     * Write code on Method

     *

     * @return response()

     */

    public function index()

    {

        $categories = Category::select("id", "name")

                        ->withCount([

                            'products as active_products_count' => function ($query) { 

                                $query->where('is_active', '1');

                            },

                        ])

                        ->get()

                        ->toArray();

 

        dd($categories);

    }

}



Output:


Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Mobile
            [active_products_count] => 2
        )
    [1] => Array
        (
            [id] => 2
            [name] => Laptop
            [active_products_count] => 2
        )
)


I hope this will help in your programming. If you have any doubt please let me know in comments.