Laravel how to fill a select with Eloquent?

1

I am 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);

In view :

{{Form::select('tipo_id',
               $tipos,
               $imovel->tipo_id,
               ['id'=>'myselect','class' =>'form-control'])}}

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 get only the nome attribute in the item and id in value ?

    
asked by anonymous 30.12.2017 / 19:56

2 answers

0

You will have to treat the array passed to the 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 the Form :: select:

{{Form::select('tipo_id',
           $tipos,
           $imovel->tipo_id,
           ['id'=>'myselect','class' =>'form-control'])}}

the select will be mounted as follows:

<select name="tipo_id">
    <option value="id">nome</option>

</select>

At the official documentation is a bit summarized, but for the find other sources which explains how to create an array-based select.

    
04.01.2018 / 13:11
0

It's very simple!

No controller should look this way:

Just reverse the order of 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);

In View - Blade

{{Form::select('tipo_id',
           $tipos,
           $imovel->tipo_id,
           ['id'=>'myselect','class' =>'form-control'])}}
    
21.06.2018 / 16:01