In Illuminate Collections, you can easily pluck a specific attribute from a collection of objects using the pluck
method. Here's how you can do it:
use Illuminate\Support\Collection;
$users = [
['id' => 1, 'name' => 'John', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Jane', 'email' => '[email protected]'],
['id' => 3, 'name' => 'Doe', 'email' => '[email protected]'],
];
Convert this array into a collection like this:
$collection = new Collection($users);
Alternatively, you can use the collect
helper function to create the collection:
$collection = collect($users);
pluck
method to retrieve a specific attribute from each object in the collection. For example, let's pluck the 'name' attribute:$names = $collection->pluck('name');
This will return a new collection containing only the 'name' attribute values:
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => John
[1] => Jane
[2] => Doe
)
)
That's it! You have successfully plucked a specific attribute from a collection of objects using the Illuminate Collections pluck
method.