pluck()

pluck() retrieves all values for a given key.

Syntax$collection->pluck('key');

The pluck() method pulls out all the values for a given key. It is ideal for turning a collection of arrays or objects into a simple list of one field.

Pass a second key to use as the resulting collection's keys.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A controller plucks the 'email' field from a collection of User models to build a recipient list for a bulk notification.
  • A product page plucks 'name' keyed by 'id' from a collection to populate a select-box options array.
  • A permissions check plucks all 'slug' values from the current user's roles to perform a quick in_array lookup.

More examples

Extract a single field

Pulls out the 'email' value from every item, returning a flat collection of email strings.

Example · php
$users = collect([
    ['name' => 'Alice', 'email' => '[email protected]'],
    ['name' => 'Bob',   'email' => '[email protected]'],
]);

$emails = $users->pluck('email');
// => Collection ['[email protected]', '[email protected]']

Pluck with a key column

The second argument sets the key for the resulting collection, producing an id-to-name lookup map.

Example · php
$products = Product::all();

// Keyed by product id
$names = $products->pluck('name', 'id');
// => Collection [1 => 'Widget', 2 => 'Gadget', ...]

Pluck a nested attribute

Uses dot notation to reach into a nested array and extract a deeply-nested field from every item.

Example · php
$orders = collect([
    ['id' => 1, 'customer' => ['name' => 'Alice', 'city' => 'NYC']],
    ['id' => 2, 'customer' => ['name' => 'Bob',   'city' => 'LA']],
]);

$cities = $orders->pluck('customer.city');
// => Collection ['NYC', 'LA']

Discussion

  • Be the first to comment on this lesson.