Skip to main content

What is a collection?

Illuminate\Support\Collection is a wrapper around a PHP array that lets you chain operations instead of nesting array functions. Every method that transforms data returns a new collection, leaving the original untouched.
Collections are immutable. Each transformation method returns a new collection instance, so you can branch a pipeline without affecting earlier steps.

Creating collections

Eloquent’s get() always returns an Illuminate\Database\Eloquent\Collection, which extends Collection and supports all the same methods.

Essential methods

map — transform each item

filter and reject — narrow the set

After filter(), the original keys are preserved. Call values() to re-index from 0 when you need a sequential array.

first and last — retrieve one item

pluck — extract one field

groupBy — organize by a key

sortBy and sortByDesc — reorder

each — run side effects

reduce — fold to a single value

For simple sums, sum() is more readable: $cart->sum(fn ($i) => $i['qty'] * $i['price']).

reduceInto — accumulate into an object

Like reduce, reduceInto folds a collection into a result, but its callback does not need to return a value. It is useful when mutating an existing object directly.
With reduce, the callback return value becomes the next $carry, making it well suited to primitive values. With reduceInto, you keep mutating the same object, which often results in simpler code.
To accumulate into a scalar or array, pass the callback value by reference (&):

chunk — split into batches

flatMap — map then flatten one level

Method chaining

The real power of collections is composing transformations:

Working with Eloquent collections

Eloquent returns Illuminate\Database\Eloquent\Collection from get(), which extends the base Collection and adds a few extras:
Filter and sort in the database when you can. Doing it on a collection means all rows are loaded into memory first. Use where() and orderBy() on the query before calling get().

Lazy collections

LazyCollection uses PHP generators to process one item at a time, keeping memory flat regardless of how many records are in the result set.

Creating a lazy collection

Chaining on a lazy collection

Lazy collection methods are evaluated on demand, so you can chain filter(), map(), and each() without pulling everything into memory:
cursor() keeps a single database connection open for the duration of the loop. For very long-running loops, consider using chunk() to release and re-acquire the connection between batches.

Common methods at a glance

Last modified on July 13, 2026