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

Reshaping Collection Keys with Pluck, KeyBy, and Values

In Laravel, a collection stores items under keys, much like a PHP array. An item can be a full record, such as a product with an ID, name, and price. The key tells you how to find the item; the fields inside it store the product data.

Use pluck() to select fields, keyBy() to make complete items accessible by a chosen key, and values() to replace existing keys with consecutive numbers. The right choice depends on whether you want to change what each item contains, how you look it up, or only its outer key.

The examples below start with a collection of product arrays:

$products = collect([
    ['product_id' => 'prod-100', 'name' => 'Desk',  'price' => 200],
    ['product_id' => 'prod-200', 'name' => 'Chair', 'price' => 100],
]);

Use pluck() when you need selected fields

pluck() returns a collection containing a field from each item. With one argument, it keeps the selected values and assigns them consecutive number keys starting at zero:

$names = $products->pluck('name');

// ['Desk', 'Chair']

Pass a second field name to use that field as each result item’s key. This creates a compact lookup, where each key points to the selected value:

$namesById = $products->pluck('name', 'product_id');

// ['prod-100' => 'Desk', 'prod-200' => 'Chair']

Choose keyed pluck() when later code needs a mapping such as product ID to display name. Choose it without a key when the code needs only a list of values. In either case, pluck() drops the rest of each item. If later code needs the full product record, use keyBy() instead.

Laravel also lets pluck() retrieve nested fields with dot notation, such as pluck('owner.name'). The collection documentation describes field selection, optional keys, and nested access.

A duplicate key changes the result: when multiple items produce the same key, the last matching value remains. Use groupBy() when you need to retain every item that shares a key.

Use keyBy() when you need full items by key

keyBy() keeps each complete item and sets its new outer key from a field or a callback, a function that derives the key from the item. For example:

$productsById = $products->keyBy('product_id');

$desk = $productsById->get('prod-100');

// ['product_id' => 'prod-100', 'name' => 'Desk', 'price' => 200]

Here, get() retrieves the item stored under the prod-100 collection key. Use keyBy() when the caller has an identifier and needs the associated full record. Use a callback when you need to derive the key from the item instead of reading it from one field.

If several items produce the same key, keyBy() keeps only the last one. When the requirement is to keep all items with the same value, use groupBy() instead. Laravel documents these key-based lookup and duplicate-key behaviors in its collection method reference.

Use values() when the old keys no longer matter

values() keeps the items and their order, but replaces the collection’s outer keys with consecutive integers starting at zero. This is useful after filtering, because filtering can leave gaps in the original keys:

$affordable = $products
    ->filter(fn ($product) => $product['price'] values();

The resulting collection contains the chair under key 0. Without values(), filtering preserves the surviving item’s original key, 1. Call values() when later code expects sequential numeric keys or when the previous keys no longer carry useful meaning. Avoid it when those keys represent IDs or other information you still need.

Choose by the structure you need

Use pluck('field') for selected values, pluck('valueField', 'keyField') for a field-to-field lookup, and keyBy('field') when you need complete items addressed by a field. Use values() to discard existing outer keys and reindex the remaining items.

These examples operate on an existing Laravel collection. Laravel’s query builder also has a method named pluck() that retrieves selected columns from a database query, so the context matters when reading or writing code that calls it.

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 *