1$users = User::all()->pluck('field_name');
2//for keys instead of [User::all()->pluck('id');] use
3$user_ids = User::all()->modelKeys();
1// QUESTION
2When We should use Pluck method in laravel???
3
4// ANSWER
5You might often run into a situation where you have to
6extract certain values (excluding the keys) from a collection
7then you should use pluck().
8i.e (when you only need value, not the key)
9
10//Example 1
11let we have a list of results and we only need the value of one colum
12
13$attendees = collect([
14 ['name' => 'Bradmen', 'email' => 'bradmen@gmail.com', 'city' => 'London'],
15 ['name' => 'Jhon Doe', 'email' => 'doe@gmail.com', 'city' => 'paris'],
16 ['name' => 'Martin', 'email' => 'martin@gmail.com', 'city' => 'washington'],
17]);
18
19$names = $attendees->pluck('name')
20//Reult ['Bradmen', 'Jhon Doe', 'Martin'];
21
22//Example 2
23OR You can use like this
24
25$users = User::all();
26$usernames = $users->pluck('username');
27
1$collection = collect([
2 ['product_id' => 'prod-100', 'name' => 'Desk'],
3 ['product_id' => 'prod-200', 'name' => 'Chair'],
4]);
5
6$plucked = $collection->pluck('name');
7
8$plucked->all();
9
10// ['Desk', 'Chair']
1$array = [
2 ['developer' => ['id' => 1, 'name' => 'Taylor']],
3 ['developer' => ['id' => 2, 'name' => 'Abigail']],
4];
5
6$array = array_pluck($array, 'developer.name');
7
8// ['Taylor', 'Abigail'];