$orders = collect([
['status' => 'pending'],
['status' => 'completed'],
['status' => 'pending'],
['status' => 'cancelled'],
['status' => 'completed'],
['status' => 'completed'],
]);
$counts = $orders->countBy('status');
// ['pending' => 2, 'completed' => 3, 'cancelled' => 1]
// Callback
$users = User::all();
$byAge = $users->countBy(fn($u) => floor($u->age / 10) * 10);
// [20 => X, 30 => Y, 40 => Z]
// Email-домени
$emails = collect([
'john@gmail.com',
'jane@yahoo.com',
'bob@gmail.com',
'alice@gmail.com',
]);
$domains = $emails->countBy(
fn($e) => explode('@', $e)[1]
);
// ['gmail.com' => 3, 'yahoo.com' => 1]
// Розподіл за довжиною рядка
$words = collect(['hello', 'world', 'php', 'laravel', 'code']);
$lengths = $words->countBy(fn($word) => strlen($word));
// Статистика для dashboard
public function stats()
{
$orders = Order::whereDate('created_at', today())->get();
return [
'by_status' => $orders->countBy('status'),
'by_payment' => $orders->countBy('payment_method'),
'by_hour' => $orders->countBy(
fn($o) => $o->created_at->hour
),
];
}