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?
I'm severelly against using DB calls in views. And here is why:
It ain't made for that!
.Period.
If I where you (note the
if
clause) I'd like better to fulfill a regular array, being thecompany->id
the array key and any other information you may wanna for that especific key as a value. On my blade code, I'd made that way:Where "companies" would be a array passed as argument to the view by the controller.
Views aren't made to make DB consults. They are made to display data. JUST IT!
That being said:
Form::select
is the selector's name. The one you get on theInput::get
.If I didn't made myself clear, please ask down here! =D
In order to populate a dropdown menu with all the records from the RecordCompany model, you can do the following, in your view:
Explanation of the code:
Form::select
methods creates a HTML select tag.company_id
is the name of the select tag.lists
method in any model (RecordCompany in this case) generates an associative array containing the parameters passed to that method (id
andcompany_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
In View
You can view the Laravel 4 documentation for generating a drop down list here: http://laravel.com/docs/html#drop-down-lists
For Laravel 5, you can code like this :-
Controller Code
View Code