November 30, 2016 —John Koster
pluck($value, $key = null)
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.
The following code example will demonstrate the usage of the pluck
method to retrieve a collection of the product names and versions:
1<?php 2 3use Illuminate\Support\Collection; 4 5// Create a new collection. 6$collection = new Collection([ 7 ['name' => 'Laravel', 'version' => '5.1'], 8 ['name' => 'Lumen', 'version' => '5.0'] 9]);10 11// Get a list of product names.12$productNames = $collection->pluck('name');13 14// Get a list of product versions.15$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)[134]2 protected 'items' =>3 array (size=2)4 0 => string 'Laravel' (length=7)5 1 => string 'Lumen' (length=5)
and the $productVersions
variable would contains a value similar to the following output:
1object(Illuminate\Support\Collection)[134]2 protected 'items' =>3 array (size=2)4 0 => string '5.1' (length=3)5 1 => string '5.0' (length=3)
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<?php2 3$products = $collection->pluck('version', 'name');
The $products
variable would then contain a value similar to the following output:
1object(Illuminate\Support\Collection)[134]2 protected 'items' =>3 array (size=2)4 'Laravel' => string '5.1' (length=3)5 'Lumen' => string '5.0' (length=3)
∎
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.