Laravel pluck method example; Through this tutorial, you will learn what is eloquent pluck() method and how to use pluck with single or multiple columns with Laravel array or collection.
As well as will take several examples of laravel eloquent pluck query for an explanation.
Laravel Pluck() – Laravel Pluck Method Example
The laravel eloquent pluck() method is used to extract values from array or collection.
For example, 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 the 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: Laravel Pluck Multiple Columns – Extract Multiple Value From Collection
Now if you may want to extract only the multiple values from the collection or column 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.