Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating a dropdown menu with database results in Laravel 4

I'm trying to populate a drop down menu with database results in Laravel 4. I'm extremely new to Laravel. This is actually my first site and I'm learning as I go. So, please tell me if I'm using the wrong terminology or not enough information.

I've got a database of company info and I need users to be able to choose a company from a dropdown. Or if the company isn't in the database to add it.

For the select menu, it needs to go like this:

[company name result]

And I'm using this code in my controller:

$companies = RecordCompany::get();
$company_selector = array();

foreach($companies as $company) {
   $company_selector[$company->id] = $company->id;
   $company_selector[$company->company_name] = $company->company_name;
}

return View::make('admin.record_new', array('company_selector' => $company_selector));

And this is what I've got in my view:

@if(count($client_selector)>0)
   {{ Form::select('company_id', $company_selector, array_values($company_selector)[0]) }}
@endif 

Disclaimer: I found this code online.

First, I don't understand how it will populate the value and option text without my telling it where to put the data.

Second, the error that's coming back is unexpected . When I take out the [0] in the form code, it tells me that $company_selector is undefined.

What am I doing wrong here?

like image 635
jerauf Avatar asked Feb 21 '14 14:02

jerauf


1 Answers

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')) }}

Note: In Laravel 5, the method lists has been deprecated. Use pluck instead.

Explanation of the code:

  1. The Form::select methods creates a HTML select tag.
  2. company_id is the name of the select tag.
  3. 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: http://laravel.com/docs/html#drop-down-lists

like image 126
SUB0DH Avatar answered Nov 04 '22 16:11

SUB0DH