Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

Transforming Data with Laravel Collection Methods

In Laravel, a collection is an object that wraps an array of items and provides methods for changing or selecting those items. Methods such as map, filter, reject, and transform let you shape data in memory, including data returned by database queries. Laravel’s collection documentation describes the collection as a fluent interface, meaning you can chain method calls into a sequence.

That sequence is a pipeline: each method receives the collection produced by the previous one. Use map to change every item and keep the original collection, filter to keep items that pass a condition, reject to discard items that match a condition, and transform to replace the items in the existing collection.

Use map to change every item

map calls a callback for each item and returns a new collection containing the callback’s results. Use map to create a new data shape while keeping the original collection available.

$displayRows = $orders->map(fn ($order) => [
    'id' => $order['id'],
    'label' => $order['name'],
]);

Here, each order becomes an array with only an id and a label. The original $orders collection remains available for another operation. You can also chain collection methods, applying map to the results of a preceding method call.

Returning an array with named keys from the callback does not make those fields collection keys. Each mapped item is still an array. To build a collection keyed by a field, use mapWithKeys; to select a field and optionally key the results by another, use pluck. This discussion of collection mappings explains the difference.

Use filter to keep matching items

filter retains items whose callback returns a truthy value. PHP treats a truthy value as true when deciding whether to keep an item. Use filter when the condition describes what should remain.

$visibleOrders = $orders->filter(
    fn ($order) => $order['is_visible']
);

You can place filter before map so the callback only reshapes the items that pass the condition:

$displayRows = $orders
    ->filter(fn ($order) => $order['is_visible'])
    ->map(fn ($order) => [
        'id' => $order['id'],
        'label' => $order['name'],
    ]);

Without a callback, filter removes values PHP treats as false. PHP treats null and false that way, along with 0. Use an explicit condition when those values are valid data. The behavior of callback-free filtering is also noted in this Laravel collections overview.

Use reject to discard matching items

reject removes items whose callback returns a truthy value and keeps the rest. Use it when the condition naturally describes what to exclude.

$activeOrders = $orders->reject(
    fn ($order) => $order['is_archived']
);

You can first discard archived orders, then keep visible ones, and finally reshape each remaining order:

$displayRows = $orders
    ->reject(fn ($order) => $order['is_archived'])
    ->filter(fn ($order) => $order['is_visible'])
    ->map(fn ($order) => [
        'id' => $order['id'],
        'label' => $order['name'],
    ]);

Choose between filter and reject based on the clearest condition. For example, keep visible items with filter, or discard archived items with reject. The two methods express opposite decisions, so choose the one that makes the condition easiest to read.

Use transform to replace items in the same collection

transform applies a callback to every item and replaces the items in the existing collection. Use it when you intend to overwrite that collection’s contents and do not need its original items afterward.

$orders->transform(fn ($order) => [
    'id' => $order['id'],
    'label' => $order['name'],
]);

After this call, $orders contains the transformed items. By contrast, map returns a separate collection and leaves $orders unchanged. This distinction matters when another part of the code still needs the original data; guidance on transform and in-place changes warns that replacing the collection’s contents can affect later code that uses it.

Choose the method by the change you need

Data-shaping task Method Effect
Change every item and keep the original collection map Returns a new collection
Keep items that pass a condition filter Returns a filtered collection
Discard items that match a condition reject Returns a filtered collection
Replace items in the current collection transform Changes the existing collection

When you need to select items and reshape them, use filter or reject first to choose which items stay, then use map to choose what each item looks like. Use transform when you intend to replace the current collection. If you need the original data later, use map instead.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *