To get an array for all 7 days, regardless of whether entries were added or not, you can use a left join with a subquery that selects the count of products for each day. Here's an example:
public function getProductsWeek()
{
$dates = collect();
$startDate = Carbon::now()->subDays(7)->startOfDay();
$endDate = Carbon::now()->endOfDay();
while ($startDate <= $endDate) {
$dates->push($startDate->format('Y-m-d'));
$startDate->addDay();
}
return DB::table('dates')
->leftJoinSub(
Product::selectRaw('DATE(created_at) as date, COUNT(*) as products')
->where('created_at', '>=', Carbon::now()->subDays(7))
->groupBy('date'),
'products',
'dates.date',
'=',
'products.date'
)
->orderBy('dates.date', 'ASC')
->get(['dates.date', DB::raw('COALESCE(products.products, 0) as products')])
->toArray();
}
This code creates a collection of all the dates in the last 7 days, then performs a left join with a subquery that selects the count of products for each day. The COALESCE function is used to replace null values with 0.