Laravel 5 Collections: Retrieving Collection Element Values With pluck

April 22, 2018 —John Koster

The pluck method is used to retrieve the a list of values from the collection. It defines two parameters: $value and $key. The $value indicates which property should become the value in the resulting collection and the $key parameter indicates which property should become the key in the resulting collection.

#Signature

1public function pluck(
2 $value,
3 $key = null
4);

#Example Use

The following code example will demonstrate the usage of the pluck method to retrieve a collection of the product names and versions:

1use Illuminate\Support\Collection;
2 
3// Create a new collection.
4$collection = new Collection([
5 ['name' => 'Laravel', 'version' => '5.1'],
6 ['name' => 'Lumen', 'version' => '5.0']
7]);
8 
9// Get a list of product names.
10$productNames = $collection->pluck('name');
11 
12// Get a list of product versions.
13$productVersions = $collection->pluck('version');

After the above code has been executed, the $productNames variable would contain a value similar to the following output:

1object(Illuminate\Support\Collection)
2 protected 'items' =>
3 array
4 0 => string 'Laravel'
5 1 => string 'Lumen'

and the $productVersions variable would contains a value similar to the following output:

1object(Illuminate\Support\Collection)
2 protected 'items' =>
3 array
4 0 => string '5.1'
5 1 => string '5.0'

The following code example will return a new collection with the version as the value and the product name as the key of the resulting collection:

1$products = $collection->pluck('version', 'name');

The $products variable would then contain a value similar to the following output:

1object(Illuminate\Support\Collection)
2 protected 'items' =>
3 array
4 'Laravel' => string '5.1'
5 'Lumen' => string '5.0'

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.