How to use pluck() in Laravel 8 ?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
How to use pluck() in Laravel 8

Today now in this tutorial,i will explain with you about how we can use pluck method in our laravel 8 application. Here i will show you a simple example of pluck query builder example in laravel 8 application. We have a table to get array in values by using laravel pluck method.

So it can get value by column and key by using pluck method. Here pluck method will returned a collection of single column or specify a custom key column by following example.

Now here the use pluck example.

Example 1

So here example single column for the returned Collection

/**
 * Show the application dashboard.
 *
 * @return \Illuminate\Contracts\Support\Renderable
 */
public function index(){
   
   $ids = \DB::table('posts')->pluck('id');

   dd($ids);
}

Output

array:[
    0 => 1
    1 => 2
    2 => 3
   ]
Example 2

Now here example specify a custom key column for the returned Collection

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

   dd($users);
}

Output

array:4 [
    1 => "abc"
    2 => "xyz"
    3 => "mno"
  ]

Read Also : How to Implement Chartjs in Laravel?

I hope it will help you. Also you can follow us on Facebook

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →