Skip to main content

Example 4. Extensive Collection Usage

Premium
5 min read

Comments & Discussion

DS
Dmytro Sakharuk ✓ Link copied!

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
]);
 
}
M
Modestas ✓ Link copied!

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!

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.