Laravel how to fill a select with Eloquent?
I'm using Laravel 5.5
and trying to fill a input select
with Eloquent and using the following code:
No controller
:
$tipos = Tipo::pluck('nome', 'id');
return view('teste')->with('tipos', $tipos);
Na view
:
{{Form::select('tipo_id',
$tipos,
$imovel->tipo_id,
['id'=>'myselect','class' =>'form-control'])}}
And in this way, each item of checkbox
turns an object as follows:
{"id":1,"nome":"casa","created_at":"2017-12-29 18:09:45","updated_at":"2017-12-29 18:09:45"}
How do I make it only the nome
attribute in the item and id
in the value?
2 answers
You will have to treat the array passed to select to form a new associative array. The key being the id and the name the value.
$tipos = Tipo::pluck('nome', 'id');
$tipo_associativo = [];
foreach($tipos as $key => $tipo){
$tipo_associativo[$tipo['id']] = $tipo["nome"];
}
return view('teste')->with('tipos', $tipo_associativo);
Now when you pass this new array to Form:: select:
{{Form::select('tipo_id',
$tipos,
$imovel->tipo_id,
['id'=>'myselect','class' =>'form-control'])}}
Select will be mounted as follows:
<select name="tipo_id">
<option value="id">nome</option>
</select>
Na official documentationta a little summarized, but Da Pra find other sources that explains Well how to create an array-based select.
It's very simple!
In controller
should look like this:
Just invert the order of the factors and get a different result. It is not necessary to go through the object!
$tipos = Tipo::pluck('id', 'nome');
return view('teste')->with('tipos', $tipos);
Na View
- Blade
{{Form::select('tipo_id',
$tipos,
$imovel->tipo_id,
['id'=>'myselect','class' =>'form-control'])}}