groupBy()

groupBy() groups items by a key or callback result.

Syntax$collection->groupBy('key');

The groupBy() method groups the collection's items by a given key. The result is a collection of collections, keyed by the grouping value.

You can also pass a callback to compute the group key dynamically.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • An admin dashboard groups a collection of orders by their 'status' field to display separate tables for pending, shipped, and delivered orders.
  • A reporting feature groups log entries by date so each date becomes a section heading in the exported report.
  • A scheduling page groups appointments by the assigned staff member so each practitioner's calendar is built from one query result.

More examples

Group by a string key

Groups the collection by the 'status' key, producing a collection of collections keyed by each status value.

Example · php
$orders = collect([
    ['id' => 1, 'status' => 'pending'],
    ['id' => 2, 'status' => 'shipped'],
    ['id' => 3, 'status' => 'pending'],
]);

$grouped = $orders->groupBy('status');
// 'pending' => [{id:1}, {id:3}]
// 'shipped' => [{id:2}]

Group with a callback

Uses a closure to derive the grouping key (year-month string) from each Eloquent model's timestamp.

Example · php
$invoices = Invoice::all()
    ->groupBy(fn($inv) => $inv->created_at->format('Y-m'));

// ['2025-01' => [...], '2025-02' => [...]]

Count items in each group

Chains map() after groupBy() to collapse each sub-collection into a count, building a department-size summary.

Example · php
$byDept = Employee::all()->groupBy('department');

$counts = $byDept->map(fn($group) => $group->count());
// => ['Engineering' => 12, 'Marketing' => 5, ...]

Discussion

  • Be the first to comment on this lesson.