Laravel Pluck Method Example
Laravel 21-Dec-2020

Laravel Pluck Method Example

In this laravel pluck method example, you will learn laravel eloquent pluck() method.

As well as will take several examples of laravel eloquent pluck query for an explanation.

The laravel eloquent pluck() method is used to extract values from array or collection.

Suppose you have the following collection:

$users = collect([
    ['name' => 'Tome Heo', 'email' => 'tom@heo.com', 'city' => 'London'],
    ['name' => 'Jhon Deo', 'email' => 'jhon@deo.com', 'city' => 'New York'],
    ['name' => 'Tracey Martin', 'email' => 'tracey@martin.com', 'city' => 'Cape Town'],
    ['name' => 'Angela Sharp', 'email' => 'angela@sharp.com', 'city' => 'Tokyo'],
    ['name' => 'Zayed Bin Masood', 'email' => 'zayad@masood.com', 'city' => 'Dubai'],
]);

Now if you may want to extract only the cities of the users. You can do something like following:

$cities = $users->pluck('city')

Example 1: Extract Single Value From Collection Using Pluck()

Now if you may want to extract only the single value from the collection using pluck() method. You can do something like the following:

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
    
   $name = User::pluck('name');
   
   dd($name);
}

Example 2: Extract Multiple Value From Collection Using Pluck() in Laravel

Now if you may want to extract only the multiple value from the collection using pluck() method. You can do something like the following:

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
    
   $data = User::pluck('name', 'id');
   
   dd($data);
}

Example 3: Laravel Pluck Relationship

If you may want to extract values from the collection with relationship objects using pluck() method. You can do something like the following:

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
    
   $users = User::with('profile')->get();
   $bio = $users->pluck('profile.bio'); // Get all bio of all users profile
   
   dd($bio);
}

Conclusion

In this laravel pluck() example, here you have learned how to use laravel pluck method.