Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Kris01's avatar

Group by Week

How can I group by week the orders in the last month with the date displayed being the start of the week? For example I want to have

2022-12-1 : 5
2022-12-7 : 10
2022-12-14 : 13
2022-12-21 : 34
2022-12-28 : 89
0 likes
4 replies
Tray2's avatar

The easiest would be to use concat, and count.

SELECT CONCAT(YEAR(created_at), "-",MONTH(created_at), "-", WEEK(created_at))  AS WEEK, count(id)
FROM orders
GROUP BY 1;

1 like
ene's avatar

@Kris01

$orders = Order::where('created_at', '>=', Carbon::now()->subMonth())
    ->get()
    ->groupBy(function($order) {
        return Carbon::parse($order->created_at)->startOfWeek();
    });

Please or to participate in this conversation.