Level 39
Try replacing $exports with the following:
$exports = $exportsdefault->groupBy('date')->map(function ($item) {
return $item->pluck('count')->sum();
})->values()->toArray();
1 like
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Laravel group by date show 0 when no data for the charts
$today = today();
$dates = [];
for($i=1; $i < $today->daysInMonth + 1; ++$i) {
$dates[] = \Carbon\Carbon::createFromDate($today->year, $today->month, $i)->format('Y-m-d');
}
$year = Carbon::now()->format('Y');
$month = Carbon::now()->format('m');
$daysCount = Carbon::createFromDate($year, $month, 1)->daysInMonth;
$exportsdefault = Shipment::select(DB::raw("COUNT(id) as count "), DB::raw('DATE(created_at) as date') )
->Where('shipment_type' ,'Export')
->where('company_id',2)
->whereBetween('created_at', ['2022-10-01', '2022-10-31'])
->groupBy('date')
->pluck('count');
$exports = array_replace(array_fill_keys(range(0,$daysCount), 0), $exportsdefault->toArray());
array:32 [▼
0 => 5
1 => 3
2 => 2
3 => 10
4 => 1
5 => 4
6 => 1
7 => 2
8 => 0
9 => 0
10 => 0
11 => 0
12 => 0
13 => 0
14 => 0
15 => 0
16 => 0
17 => 0
18 => 0
19 => 0
20 => 0
21 => 0
22 => 0
23 => 0
24 => 0
25 => 0
26 => 0
27 => 0
28 => 0
29 => 0
30 => 0
31 => 0
]
Where it groups all the data according to the dates and shows in the beginning. What I want is to show 0 when there is no data. for example :
array:32 [▼
0 => 0
1 => 5
2 => 0
3 => 3
4 => 10
5 => 0
6 => 1
7 => 4
8 => 1
9 => 0
10 => 0
11 => 0
12 => 0
13 => 0
14 => 0
Please or to participate in this conversation.