Using Laravel Pluck To Extract Certain Values
Laravel Collection is the best part of the Laravel framework which I enjoy during Laravel development. Laravel Pluck method is part of the Laravel Collections.
The pluck helper method is used to retrieve a list of specific values from a given $array. It is most useful when used against arrays of objects, but will also work with arrays just as well.
You might often run into a situation where you have to extract certain value from a collection.
In this post, I will show you how you can use
pluck() method of Laravel collections to extract selected part of data.
Consider the below example, we have got a list of event attendees with their name, email, and city.
$attendees = collect([ ['name' => 'Tome Heo', 'email' => '[email protected]', 'city' => 'London'], ['name' => 'Jhon Deo', 'email' => '[email protected]', 'city' => 'New York'], ['name' => 'Tracey Martin', 'email' => '[email protected]', 'city' => 'Cape Town'], ['name' => 'Angela Sharp', 'email' => '[email protected]', 'city' => 'Tokyo'], ['name' => 'Zayed Bin Masood', 'email' => 'z[email protected]', 'city' => 'Dubai'], ]);
Now we want to extract only the name of the attendees. You can do something like below.
$names = $attendees->pluck('name') // ['Tome Heo', 'Jhon Deo', 'Tracey Martin', 'Angela Sharp', 'Zayed Bin Masood'];
Pretty straight forward. We can also use
pluck() method on collection of objects like below.
$users = User::all(); $usernames = $users->pluck('username');
Even shorter, you can chain the method.
$users = User::all()->pluck('username');
You can also use
pluck() method on nested objects like relationships with dot notation.
$users = User::with('profile')->get(); $bio = $users->pluck('profile.bio'); // Get all bio of all users profile
Laravel Pluck method can be very useful when you extract certain column values without loading all the columns.
You can benefit from the Laravel pluck method in the blade views as well. For example, if you would like to select all options under a multiselect box, you can use this method in conjunction with the
in_array() method of PHP to determine which value to select.
That’s it for now if you have any question please leave in the comment box below.