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

Nielson's avatar
Level 14

How to itierate over a grouped collection and return value

Hi guys,

I've been tinkering around with some data that I finally managed to group as I want it to, but I can't figure out how to do this next part.

So I got this dataset:

{
10: [
{
week: "10",
Booket: 0
},
{
week: "10",
Booket: 18
},
{
week: "10",
Booket: 10
}
],
11: [
{
week: "11",
Booket: 0
},
{
week: "11",
Booket: 5
},
{
week: "11",
Booket: 5
},
{
week: "11",
Booket: 0
},
{
week: "11",
Booket: 15
}
],
12: [
{
week: "12",
Booket: 0
},
{
week: "12",
Booket: 5
},
{
week: "12",
Booket: 14
}
],
}

I want to iterate over each week, add the numbers from "Booket" and return them so I would get something like this:

{
10: [
{
week: "10",
Booket: 28
},
],
11: [
{
week: "11",
Booket: 25
},
],
12: [
{
week: "12",
Booket: 19
},
],

This is my show method:

    public function show()
    {
        $bookings = Booking::where('SelectedDate', '>', Carbon::now()->firstOfYear())
                            ->where('TypeID', 3)
                            ->where('TemplateID', 18)
                            ->where('Interval', '07:00-12:00')
                            ->selectRaw('DATE_FORMAT(SelectedDate, "%V") as week, Booket')
                            ->orderBy('week', 'asc')
                            ->get();

        $result = $bookings->groupBy('week');

        $result = $result->groupBy(function ($item) {
            return $item['Booket'];
        })->all();


        return view('bookings.show', compact('result'));
    }

This is so I can return it to a Chart.js graph which shows the booking count for each week.

Can anyone chime in on this with a bit of expertise and fresh mind? :)

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

Rather than working with the data in PHP, your query can sum the data you need:

$bookings = Booking::where('SelectedDate', '>', Carbon::now()->firstOfYear())
    ->where('TypeID', 3)
    ->where('TemplateID', 18)
    ->where('Interval', '07:00-12:00')
    ->selectRaw('DATE_FORMAT(SelectedDate, "%V") as week, SUM(Booket) as Booklet')
    ->orderBy('week', 'asc')
    ->groupBy('week')
    ->get();
1 like
Nielson's avatar
Level 14

Thanks @tykus ! That was exactly what I wanted. Sometimes it's the approach that does the job! :)

Please or to participate in this conversation.