In this tutorial you will learn about the Laravel Pluck Method Example and its application with practical example.
In this laravel pluck method tutorial, I’ll show you how to use laravel eloquent pluck() method. In this tutorial I’ll demonstrate the use of laravel pluck method.
Laravel Pluck Method Example
The laravel eloquent pluck() method is used to extract specified values from array or given collection.
Example:-
In this laravel pluck method tutorial we will use following collection for example:
1 2 3 4 5 6 7 |
$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'], ]); |
Let suppose now we want to extract only the cities of the users. This can be achieved using laravel pluck method as following:
1 |
$cities = $users->pluck('city') |
Extract Single Value From Collection Using Pluck()
Let suppose now we want to extract only the single value from the collection using pluck() method. This can be achieved using laravel pluck method as following:
1 2 3 4 5 6 7 8 9 10 11 |
/** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index(){ $name = User::pluck('name'); dd($name); } |
Extract Multiple Value From Collection Using Pluck() in Laravel
Let suppose now we want to extract only the multiple value from the collection using pluck() method. This can be achieved using laravel pluck method as following:
1 2 3 4 5 6 7 8 9 10 11 |
/** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index(){ $data = User::pluck('name', 'id'); dd($data); } |
Laravel Pluck Relationship
Let suppose now we want to extract values from the collection with relationship objects using pluck() method. This can be achieved using laravel pluck method as following:
1 2 3 4 5 6 7 8 9 10 11 12 |
/** * 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); } |