Collections

Collect anything

The collect helper wraps any array in a fluent object with dozens of chainable methods. Once wrapped, sorting, filtering, and reshaping need no manual loops at all.

$names = collect(["ada", "bob", "cid"]); echo $names->count(); echo $names->first();

Map and filter

The map method rebuilds every item through a callback, while filter keeps only items that pass a check. Chain values at the end to renumber keys after removals.

$result = collect([1, 2, 3, 4]) ->map(function ($n) { return $n * 2; }) ->filter(function ($n) { return $n > 4; }) ->values(); print_r($result->all());

Group by

The groupBy method clusters rows that share a field value, such as users with the same role. Each cluster keeps its original rows, ready for counting or listing.

$rows = [ ["role" => "admin", "name" => "Ada"], ["role" => "editor", "name" => "Bob"], ]; $byRole = collect($rows)->groupBy("role"); echo $byRole->count();

Lazy note

Huge datasets do not fit in memory at once, so collections can stream items one by one. The lazy method returns a lazy collection that only pulls each value when the chain actually needs it.

$big = collect(range(1, 100000))->lazy(); $first = $big->take(5); print_r($first->all());

Next: Carbon dates

Article author: Arthur Isaev