In the Laravel web application framework, the pluck
method can be used to retrieve a list of values from a given key in an array of arrays or objects.
Example 1(basic example): For example, consider the following array of objects:
1 2 3 4 5 6 7 | $users = [ { 'name': 'John', 'age': 30 }, { 'name': 'Jane', 'age': 25 }, { 'name': 'Bob', 'age': 35 } ]; |
To retrieve a list of all the user names, you could use the pluck
method as follows:
1 2 3 | $names = collect($users)->pluck('name'); |
This would return a new Illuminate\Support\Collection
instance containing the values ['John', 'Jane', 'Bob']
.
You can also pass a second argument to the pluck
method to specify a different key to use as the value for each item in the returned collection:
1 2 3 | $ages = collect($users)->pluck('age', 'name'); |
This would return a new collection with the keys and values flipped, like this:
1 2 3 | [ 'John' => 30, 'Jane' => 25, 'Bob' => 35] |
Note that the pluck
method is just one of many useful functions provided by the Illuminate\Support\Collection
class in Laravel. You can learn more about working with collections in the Laravel documentation.
Example 2: Here’s an example of how to use the pluck
method in Eloquent, the ORM (Object-Relational Mapping) included with the Laravel PHP framework:
1 2 3 4 5 6 7 8 9 | use App\Models\User; $userEmails = User::where('active', 1)->pluck('email'); foreach ($userEmails as $email) { echo $email; } |
This will retrieve a collection of all the email addresses of users who have an active status of 1, and then loop through the collection to output each email.
The pluck
method retrieves a single column from the database and returns it as a collection. If you want to retrieve multiple columns, you can use the select
method instead.
1 2 3 4 5 6 7 8 9 | use App\Models\User; $users = User::where('active', 1)->select('email', 'name')->get(); foreach ($users as $user) { echo $user->email . ': ' . $user->name; } |
This will retrieve all the email and name columns for users with an active status of 1, and then loop through the resulting collection to output the email and name for each user.