Skip to main content

Example 4. Extensive Collection Usage

Premium
5 min read
Dmytro Sakharuk avatar

Unfortunately, the code example given above does not reflect real information, trivially, the number of displayed orders for a certain period does not correspond to the number of orders in the database for the same period.

Below is a simpler and faster code that will make only 2 requests to the database, and most importantly will return true information

public function __invoke()
{
 
$orders = collect([]);
 
$periodInformation = CarbonPeriod::create(now()->subMonths(6)->startOfWeek(), '1 week', now()->endOfWeek());
 
$orderDb = Order::query()
->whereBetween('order_time', [
now()->subMonths(6)->startOfWeek(),
now()->endOfWeek()
])
->withCount('products')
->with(['user'])
->where('status', '!=', OrderStatus::CANCELLED->value)
->orderBy('status')
->get()
->groupBy(function (Order $order) {
return Carbon::parse($order->order_time)->startOfWeek()->format('Y-m-d');
});
 
foreach ($periodInformation as $period) {
$weekStart = $period->format('Y-m-d');
$weekEnd = $period->copy()->endOfWeek()->format('Y-m-d');
if (!$orderDb->has($weekStart)) {
continue;
}
$orders->push([
'week' => $weekStart.' - '.$weekEnd,
'orders' => $orderDb->get($weekStart),
]);
}
 
return view('orders.reports', [
'orders' => $orders
]);
 
}
Modestas avatar

Thank you, we will take a look into this soon and update the examples. Your previous comment showed us that we had a problem in our testing, so we will update this course with tests and corrections!