pluck laravel code example

Example 1: collection laravel filter

$collection = collect([1, 2, 3, 4]);

$filtered = $collection->filter(function ($value, $key) {
    return $value > 2;
});

$filtered->all();

// [3, 4]

Example 2: pluck array in laravel

$users = User::all()->pluck('field_name');
//for keys instead of [User::all()->pluck('id');] use
$user_ids = User::all()->modelKeys();

Example 3: when to use pluck method in laravel

// 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');

Example 4: pluck laravel

$name = DB::table('users')->where('name', 'John')->pluck('name');

Example 5: laravel pluck

$users = Users::pluck('name','email');
dd($users);

Example 6: laravel array_pluck

$array = [
    ['developer' => ['id' => 1, 'name' => 'Taylor']],
    ['developer' => ['id' => 2, 'name' => 'Abigail']],
];

$array = array_pluck($array, 'developer.name');

// ['Taylor', 'Abigail'];