Laravel Pluck() : Laravel Collection Method to extract values

Laravel Pluck() : Laravel Collection Method to extract values

Hello Users,

To extract certain values from a collection, utilize the Laravel Collections method pluck().

You may frequently want to extract certain data from the collection, in this case the Eloquent collection. The simplest solution is to loop through the collection and extract, but Laravel Collection offers strong helper methods, including the Pluck() method, which makes this task much simpler.

The pluck method returns all values associated with a particular key:

$collection = collect([
['id' => '1', 'name' => 'Raihan'],
['id' => '2', 'name' => 'Tanim'],
]);

$plucked = $collection->pluck('name');

$plucked->all();

#Output :

['Raihan', 'Tanim'];


Moreover, you can indicate how the resulting collection should be keyed.

$plucked = $collection->pluck('id', 'name');

$plucked->all();

#output:

['1' => 'Raihan', '2' => 'Tanim'];



Using "dot" notation, the pluck technique also supports fetching nested values:

$collection = collect([
'id' => '1',
'name' => 'Raihan',
'meta' => [
'key' => ['one', 'two'],
],
],
[
'id' => '2',
'name' => 'Tanim',
'meta' => [
'key' => ['three', 'four']
],
],
]);

$plucked = $collection->pluck('meta.key');

$plucked->all();

#Output :

[['one', 'two'], ['three', 'four']];


The final matching element will be added to the plucked collection if there are duplicate keys:

$collection = collect([
['id' => 1, 'name' => 'Raihan', 'role' => '101'],
['id' => 2, 'name' => 'Arik', 'color' => '102'],
['id' => 3, 'name' => 'Mehrab', 'color' => '101'],
['id' => 4, 'name' => 'Mishu', 'color' => '103'],
]);

$plucked = $collection->pluck('name', 'role');

$plucked->all();

#Output :

['Arik' => '102', 'Mehrab' => '101', 'Mishu' => '103'];


Hope this article will help to know how Laravel Pluck() method work.