Laravel Pluck Method Example

Laravel Pluck Method Example

Laravel pluck method example; Through this tutorial, 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' => '[email protected]', 'city' => 'London'],
    ['name' => 'Jhon Deo', 'email' => '[email protected]', 'city' => 'New York'],
    ['name' => 'Tracey Martin', 'email' => '[email protected]', 'city' => 'Cape Town'],
    ['name' => 'Angela Sharp', 'email' => '[email protected]', 'city' => 'Tokyo'],
    ['name' => 'Zayed Bin Masood', 'email' => '[email protected]', '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.

Recommended Laravel Posts

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *