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
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
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
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.
&):
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 returnsIlluminate\Database\Eloquent\Collection from get(), which extends the base Collection and adds a few extras:
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 chainfilter(), 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.