How to count items that are nested inside a second level groupBy?

53 Views Asked by At
$bookings = Salon::find(3)->bookings;

$bookings->groupBy(['booking_status', function ($item) {
            return \Carbon\Carbon::parse($item['created_at'])->format('Y-m');
}])->toArray();

This gives me below.

"confirmed" => [
       "2020-12" => [
         [],[],[],[]
        ]
];

However, I am looking for something like this below:

"confirmed" => [
       "2020-12" => 4
];
1

There are 1 best solutions below

2
On BEST ANSWER

Since you have two levels of grouping and want to count things in the second level then you could do:

$bookings = Salon::find(3)->bookings;

$bookings->groupBy(['booking_status', function ($item) {
    return \Carbon\Carbon::parse($item['created_at'])->format('Y-m');
}])->map(function ($dateGroup) {
   return $dateGroup->map->count();
})->toArray();