Laravel : Populating a dropdown menu with database results

In order to populate a dropdown menu with all the records from the RecordCompany model, you can do the following, in your view:

{{ Form::select('company_id', RecordCompany::lists('company_name', 'id')) }}

Explanation of the code:

The Form::select methods creates a HTML select tag.
company_id is the name of the select tag.
The second parameter is the options for the select tag. The lists method in any model (RecordCompany in this case) generates an associative array containing the parameters passed to that method (id and company_name in this case) of all the records in the model’s database table.

If you want, you can also call the lists method from the controller and then pass the value to the view, like following:

In Controller

$company_lists = RecordCompany::lists('company_name', 'id');

return View::make(‘admin.record_new’, array(‘company_lists’ => $company_lists));

In View

{{ Form::select('company_id', $company_lists) }}

You can view the Laravel 4 documentation for generating a drop down list here:


Also don't forget you need to drop in at the archive at some point this afternoon.

Nick Cave - 20,000th day on the planet Earth

(Visited 633 times, 1 visits today)