Search code examples
phplaravelcollectionseloquentlaravel-collection

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


$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
];

Solution

  • 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();