Retrieving product count for each month in the current year laravel

Viewed 81

I'm trying to count the number of orders for each month of the current year as follows

//month arrays to loop through
       $month = ['1','2','3','4','5','6', '7', '8', '9', '10', '11','12'];
//current year
        $year = Carbon::now()->year;
//variable to store each order coubnt as array.
       $new_orders_count = [];
//Looping through the month array to get count for each month in the provided year
       foreach ($month as $key => $value) {
            $new_orders_count[] = Order::whereYear('updated_at', $year)
                                  ->whereMonth('updated_at',$value)
                                  ->where(['orders.status_id'=>11])
                                  ->orWhere(['orders.status_id'=>14])
                                  ->orWhere(['orders.status_id'=>4])->count();
             }

This gives me the following result enter image description here

Note that this is returning 48 even where it should return zero or a different value from 48, for example, months 6 through to 12 have no data thus I expect the query to return zero but it is not. Why is this and how can I achieve what I need? I'm using laravel's default timestamp format for the created_at and updated_at fields

2 Answers

Try like this way. change your query

Order::whereYear('updated_at', $year)
    ->whereMonth('updated_at', $value)
    ->where(function ($query) {
        $query->whereIn('orders.status_id', [11, 14, 4]);
    })->count();

may this help ...

    //current year
    $year = Carbon::now()->year;
    //variable to store each order count as array.
    $new_orders_count = [];
    //Looping through the month array to get count for each month in the provided year
    for($i = 1; $i <= 12; $i++){
        $new_orders_count[] = Order::whereYear('updated_at', $year)
            ->whereMonth('updated_at', $i)
            ->where(function ($query) {
                $query->whereIn('orders.status_id', [11, 14, 4]);
            })->count();
    }
Related