How to pluck a specific attribute from a collection of objects in illuminate/collections?

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:

  1. First, make sure you have the Illuminate Collections namespace imported at the top of your file:
use Illuminate\Support\Collection;
  1. Create a collection of objects. For example, let's say you have an array of User objects:
$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);
  1. Now, you can use the 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 ) )
  1. You can then use the retrieved attribute values as needed. For example, you can iterate over the 'names' collection using a loop or perform other operations on it.

That's it! You have successfully plucked a specific attribute from a collection of objects using the Illuminate Collections pluck method.