laravel collection pluck
$users = User::all()->pluck('field_name');
//for keys instead of [User::all()->pluck('id');] use
$user_ids = User::all()->modelKeys();
3.89
9
// QUESTION
When We should use Pluck method in laravel???
// ANSWER
You might often run into a situation where you have to
extract certain values (excluding the keys) from a collection
then you should use pluck().
i.e (when you only need value, not the key)
//Example 1
let we have a list of results and we only need the value of one colum
$attendees = collect([
['name' => 'Bradmen', 'email' => '[email protected]', 'city' => 'London'],
['name' => 'Jhon Doe', 'email' => '[email protected]', 'city' => 'paris'],
['name' => 'Martin', 'email' => '[email protected]', 'city' => 'washington'],
]);
$names = $attendees->pluck('name')
//Reult ['Bradmen', 'Jhon Doe', 'Martin'];
//Example 2
OR You can use like this
$users = User::all();
$usernames = $users->pluck('username');
Thank you!
9
0
5
1
$array = array_pluck($array, 'developer.name', 'developer.id');
// [1 => 'Taylor', 2 => 'Abigail'];
Thank you!
1
0
3.7
10
$array = [
['developer' => ['id' => 1, 'name' => 'Taylor']],
['developer' => ['id' => 2, 'name' => 'Abigail']],
];
$array = array_pluck($array, 'developer.name');
// ['Taylor', 'Abigail'];
Thank you!
10
0
4.4
5
$collection = collect([
['product_id' => 'prod-100', 'name' => 'Desk'],
['product_id' => 'prod-200', 'name' => 'Chair'],
]);
$plucked = $collection->pluck('name');
$plucked->all();
// ['Desk', 'Chair']
Thank you!
5
0
3.75
8
$name = DB::table('users')->where('name', 'John')->pluck('name');
Thank you!
8
0
Are there any code examples left?
New code examples in category PHP