Laravel

How to Use the pluck method in Eloquent with Example

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:




To retrieve a list of all the user names, you could use the pluck method as follows:

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:

This would return a new collection with the keys and values flipped, like this:

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:

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.

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.

Leave a Comment