In this tutorial we will see the use of Eloquent Pluck method to fetch specific key values from model and populate values into Select box.

pluck() method is for Laravel Collection and more frequently for Eloquent Collection. It allows us to fetch values for given key from the collection in array.

Starting from Laravel version 5.3 lists is deprecated and pluck method is used. We can say lists is renamed as pluck since there is no change in method.

Suppose we have a user model and we want to get only ids and names of users who have not paid the bill.
and we have to populate those names  in select box  with ids as thier respective values:

1. Define a Route


Route::get('/pendingPayments', 'UserController@pendingPayments');

2. Pluck method to fetch values

We want to get ids of users only who have not paid the bill from the entire user collection.


 protected function test(Request $request)
{
    $ids = DB::table('users')->orderBy('created_at')   
           ->where('users.paid', 'no') 
          ->pluck('name','license_id');
    return view('/pendingPayments')->with(['data' => $ids])
}

Here we will get an array of ids and names in order of "created_at" which have not paid the bill using  pluck()  something like following:

3. Populate values in select box

Code of pendingPayments.blade.php  under resources/views to populate select box. In this option will be the names and value will be the ids of users.


<div class="form-group required mb-3">
    <p class='text-sm'> <strong>LicenseID:</strong> </p>
          <select name="licenseid" id="licenseid" class="form-select text-sm">
                @foreach ($ids as $key => $value)
                      <option  value="{{ $key }}"> {{ $value }}  </option>
                @endforeach            
          </select>                                            
</div>

After hitting the specified route , we will get a view something like following :

here is a short description of populating select box using Pluck method on Eloquent model.