How to fill a select with Eloquent?



  • I'm using it Laravel 5.5 and trying to fill out 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 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 attribute only nome No item and id No value?



  • You will have to treat the past array to the select so that it forms a new associative array. Being the key 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'])}}

    will be mounted the select as follows:

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

    </select>

    Na https://laravel.com/docs/4.2/html#drop-down-lists but from the http://laravel-recipes.com/recipes/163/creating-a-select-box-field which explains how to create an array-based select.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2