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

Shaping Laravel Collections with Only, Except, and Pluck

In Laravel, a collection is an object with methods for working with a group of values, often records stored in an array. A key is the name or number Laravel uses to identify an entry. only(), except(), and pluck() shape collection values in different ways: only() keeps entries with specified keys, except() removes entries with specified keys, and pluck() gets a value from each item. For plain PHP arrays, Laravel provides corresponding Arr helpers.

only() and except() use the keys of the collection or array you call them on. pluck() looks inside each item for a value. It can also use another value from that item as the key for the result.

only() and except() filter outer keys

For an array that pairs named keys with values, or a collection built from that array, only() keeps the requested key/value pairs in the array or collection itself. except() returns the pairs left after removing the requested keys. Laravel documents both collection methods and the matching Arr helpers for arrays in its Collections documentation.

$profile = [
    'name' => 'Ada',
    'email' => 'ada@example.test',
    'token' => 'secret',
];

$publicFields = Arr::only($profile, ['name', 'email']);
// ['name' => 'Ada', 'email' => 'ada@example.test']

$withoutSecret = collect($profile)
    ->except(['token'])
    ->all();
// ['name' => 'Ada', 'email' => 'ada@example.test']

Both methods return a filtered result and leave the original array or collection unchanged. Use Arr::only() or Arr::except() to get an array result. Use the collection methods to keep working with a collection.

A “key” identifies an item in the collection itself. If $rows is a list of records with numeric positions, collect($rows)->only(['name']) looks for a collection key named name. It does not keep the name field from every record.

To keep several fields from every row, filter each row separately. For example, map() runs a function on each item, and Arr::only() selects fields from that item:

$publicRows = collect($rows)
    ->map(fn (array $row) => Arr::only($row, ['name', 'email']));

pluck() extracts a value from every item

Pass the value name as the first argument to pluck() to extract it from each item in a list. Laravel’s array helper documentation also shows dot notation, where dots separate keys along a path to a value inside a nested array.

$developers = [
    ['developer' => ['id' => 1, 'name' => 'Taylor']],
    ['developer' => ['id' => 2, 'name' => 'Abigail']],
];

$names = collect($developers)->pluck('developer.name');
// Collection containing 'Taylor' and 'Abigail'

$namesById = Arr::pluck($developers, 'developer.name', 'developer.id');
// [1 => 'Taylor', 2 => 'Abigail']

The third argument to Arr::pluck() sets the key for each extracted value. In the example, Laravel reads developer.name for each result’s value and developer.id for its key. On a collection, pluck() returns a collection; Arr::pluck() returns an array.

only() and except() select or exclude entries by their outer keys. pluck() gathers values from inside items and can arrange them under an optional key extracted from each item.

Choose the method by the level you want to shape

Method What it works on Collection method Array helper
only() Keeps entries with specified outer keys $collection->only($keys) Arr::only($array, $keys)
except() Excludes entries with specified outer keys $collection->except($keys) Arr::except($array, $keys)
pluck() Extracts a value from each item, optionally using another value as the result key $collection->pluck($value, $key) Arr::pluck($array, $value, $key)

One exception matters when you work with database models, objects that represent database records. Laravel’s Eloquent collection is the collection type for these models; its only() and except() methods use model primary keys. The Eloquent collections documentation describes that behavior, so those methods do not always filter ordinary outer array keys when the value is an Eloquent collection.

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 *