Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 67 ยท Eloquent ORM

Collections

Use Laravel collections to transform data fluently with map, filter, reduce, groupBy, pluck and sortBy, learn higher-order messages and lazy collections, and build your own.

Almost every Laravel feature that returns "several things" returns a collection: Post::all(), $user->posts, request()->collect('tags'), the result of DB::table()->get(). A collection is a thin wrapper around an array that adds dozens of chainable methods for transforming data. Instead of nested loops and temporary variables, you describe what you want as a pipeline: take these orders, keep the paid ones, group them by customer, sum each group.

This lesson shows the core methods, the helpful quirks you need to know (such as filter keeping keys), the shorthand called higher-order messages, and lazy collections, which process huge or endless data one item at a time. Collections build directly on PHP's own array functions, so it helps to know the functional array functions first. Laravel code is shown read-only; the TryIt blocks use a hand-written collection class so you can see that there is no magic inside.

Creating and chaining

The collect() helper wraps any array. Every transforming method returns a new collection and leaves the original unchanged, so you can chain calls:

PHP
$orders = collect([
    ['id' => 1, 'customer' => 'Ada',   'total' => 40, 'status' => 'paid'],
    ['id' => 2, 'customer' => 'Linus', 'total' => 15, 'status' => 'pending'],
    ['id' => 3, 'customer' => 'Ada',   'total' => 25, 'status' => 'paid'],
]);

$revenue = $orders
    ->where('status', 'paid')
    ->sum('total');                 // 65

$names = $orders->pluck('customer')->unique()->values();   // ['Ada', 'Linus']

Compare that with the loop version, which needs an accumulator, an if and a result array. The chain reads top to bottom as a description of the data flow.

flowchart LR
    A["collect($orders)"] --> B["where('status', 'paid')"]
    B --> C["groupBy('customer')"]
    C --> D["map: sum totals"]
    D --> E["sortByDesc"]
    E --> F["all() / toArray()"]

Each step returns a new collection, so the original data is never changed.

The methods you will use most

Transforming: map applies a function to every item and returns the results; flatMap maps and flattens one level; pluck('name') extracts one field (pluck('name', 'id') keys it by id); keyBy('id') re-keys items; values() renumbers keys from zero.

Filtering: filter(fn) keeps items where the function returns true, reject(fn) keeps the others, where('status', 'paid') and whereIn('id', [1, 2]) are shorthands for arrays and objects, unique() removes duplicates, partition(fn) splits in two at once.

Aggregating: sum('total'), avg('total'), min, max, count, reduce(fn, $initial) for anything custom, countBy() for tallies.

Grouping and sorting: groupBy('customer') returns a collection of collections, sortBy('total') and sortByDesc('total') sort by a field or a closure, chunk(3) splits into groups of three.

Reading: first(), first(fn), last(), firstWhere('id', 3), contains(...), isEmpty(), take(5).

Flow helpers: each(fn) runs a side effect (return false to stop early), tap(fn) peeks in the middle of a chain without changing it, pipe(fn) passes the whole collection to a function and returns its result, when(cond, fn) adds a step conditionally.

The filter() key trap

filter and where keep the original keys. After removing items you can be left with [0 => 'a', 2 => 'c']. That is harmless in PHP but changes the JSON: a list with gaps encodes as an object ({"0":"a","2":"c"}) instead of an array. Add ->values() whenever the result is sent as JSON or when you rely on positions.

Eloquent collections

Query results are an Illuminate\Database\Eloquent\Collection, a subclass with extra model-aware methods such as modelKeys(), contains($model), load('author') (see eager loading) and fresh(). Everything in this lesson works on them too.

One performance rule: a collection method runs in PHP after all rows are loaded. Post::all()->where('published', true) fetches every row, then filters in memory. Post::where('published', true)->get() lets the database do it. Use SQL for filtering and aggregating big tables (querying with Eloquent) and collections for shaping the rows you really need.

Build one yourself

A collection is mostly a wrapper around array functions. This version has the methods above, keeps its source array private and returns a new object from every transformation, like Laravel's:

PHP A hand-written Collection class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The last two lines show the key trap for real: the only pending order sits at key 1, so json_encode produces an object ({"1":2}) instead of a list, until values() renumbers it.

Higher-order messages

Many chains do nothing but call one method or read one property on every item. Laravel offers a shorthand called higher-order messages: instead of passing a closure, read the property or call the method on the collection method itself.

PHP
$users->each->markAsVip();          // same as ->each(fn ($u) => $u->markAsVip())
$users->map->name;                  // same as ->map(fn ($u) => $u->name)
$orders->sum->total;                // same as ->sum(fn ($o) => $o->total)
$orders->filter->isPaid();          // keep items where isPaid() is truthy
$users->sortBy->lastLogin;

It works through PHP's magic methods: reading ->each on the collection returns a small proxy object whose __get and __call turn your property or method name into a closure and call the real method with it. It reads well for simple cases; when you need any condition or arithmetic, a normal closure is clearer. Only a fixed list of methods supports it (map, each, filter, sum, sortBy, groupBy, contains and others).

PHP Higher-order messages in thirty lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

$orders->sum->total first reads sum, which returns a proxy; reading total on the proxy calls sum() with a closure. Nothing more than that.

Lazy collections

A normal collection holds every item in memory. For a million log lines or a 2 GB CSV that is impossible. A LazyCollection wraps a PHP generator: it produces one item at a time, and each chained step is applied to that single item before the next one is read. Memory stays flat, and when you stop early (take(10)), the rest is never read.

PHP
use Illuminate\Support\LazyCollection;

LazyCollection::make(function () {
    $handle = fopen(storage_path('logs/huge.log'), 'r');
    while (($line = fgets($handle)) !== false) {
        yield $line;
    }
})
    ->filter(fn ($line) => str_contains($line, 'ERROR'))
    ->take(20)
    ->each(fn ($line) => print($line));

Post::lazy()->each(fn ($post) => ...);   // chunked query, one model at a time
Post::cursor();                          // lazy collection over a single query
$collection->lazy();                     // turn an existing collection lazy

The trade-off: lazy collections can only be iterated forward, and some methods (sortBy, groupBy) must read everything first, which defeats the point. Use them for streaming, not for sorting a table.

PHP Lazy vs eager: what gets processed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The source is an endless counter, yet the pipeline finishes: after the third even square has been produced, take stops pulling, so numbers beyond 6 are never even read. An eager collection could never process an infinite range.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does $collection->filter(fn ($n) => $n > 1) do to the keys of the items that remain?

    filter preserves keys. A list with gaps becomes a JSON object, so call values() when you need a plain list.
  2. 2. Why is Post::all()->where('published', true) a poor choice for a big table?

    The collection method runs in memory after all rows are fetched. Post::where('published', true)->get() filters in SQL.
  3. 3. What do higher-order messages like $users->each->markAsVip() rely on in PHP?

    Reading the method name as a property returns a proxy, and the property or method you call next is turned into a closure for the real collection method.
  4. 4. When is a LazyCollection the right tool?

    Lazy collections wrap generators, so memory stays small and early exits skip the rest. Methods like sortBy and groupBy need all items and negate the benefit.

Summary

  • A collection wraps an array in a fluent API (map, filter, reduce, groupBy, pluck, sortBy, sum...); transformations return new collections.
  • filter and where keep keys, so add values() before encoding lists as JSON.
  • Eloquent results are collections with extra model methods, but filter in SQL when the table is large.
  • Higher-order messages ($orders->sum->total) are a shortcut built from __get and __call proxies.
  • LazyCollection, lazy() and cursor() stream items through generators with constant memory.
  • This is the last lesson of the Eloquent chapter; next you will protect your app with authentication.

Next: Authentication Overview and Starter Kits