What is Laravel Pluck?
Today, we will learn What is Laravel Pluck? and how to use it. The Laravel pluck method is most useful when you extract certain column values without loading all the columns. pluck is a helper function with part of the Laravel Collections. Laravel pluck to extract certain values. The laravel collection is the most used and the best part of the Laravel application.
The pluck helper function is used to retrieve a list of specific values from a given array. when we used it against arrays of objects. but we will also work with array just as well. In this post, we will learn how you can use pluck() Laravel collections to extract selected parts of data.
We have got a list of event user details with their name, email, and age.
User details
$userDetail = collect([
['name' => 'joi', 'email' => 'joi@devnote.com', 'age' => 21],
['name' => 'die', 'email' => 'die@devnote.com', 'age' => 20],
['name' => 'emily', 'email' => 'emily@devnote.com', 'age' => 22],
['name' => 'wotsan', 'email' => 'wotsan@devnote.com', 'age' => 21],
['name' => 'kell', 'email' => 'kell@devnote.com', 'age' => 24],
]);
$names = $userDetail->pluck('name') Output: ['joi', 'die', 'emily', 'wotsan', 'kell'];
Now, We use the pluck() method for the collection of objects.
$users = User::all(); $usernames = $users->pluck('username'); ===OR=== $users = User::all()->pluck('username');
We can also use the pluck() method with nested objects.
$users = User::with('profile')->get();
$detail = $users->pluck('profile.detail'); // Get all detail of all users profile