Popular select with database values

Asked

Viewed 591 times

3

I need a select in the form with values from another table. Type:

<select>
   <option value="29">Frentista</option>
</select>

I wrote my select like this:

{{ Form::select('set_id_fk', $setores, null, ['class'=>'form-control input-lg']) }}

But in the view is getting like this:

{"set_id": 29, "set_nome": "Frentista"}

I’m using the "laravelcollective/html": "^5.3.0" in my project.

Can someone help me?

  • Your Laravel is the 5.3?

  • Tell me the version of yours Laravel and the model Eloquent with the fields to post a solution, although your doubt may already exist a duplicate (question that already contains some answer that can also solve your problem), I realized that you posted in the answer below but, in my comment did not make any comments! I can help you clear if you want?

2 answers

1


If you have a table with unique types and identifiers becomes easy, assuming I have the following table:

id descricao
1   Álcool
2   Gasolina
3   Disel

and from this have my model created, assuming the model name Tipocombustible, to assemble the array of items just use the Pluck method as follows:

$arrayTipoCombustivel = App\Models\TipoCombustivel::pluck('descricao', 'id');

in this way, I would have the $arrayTipoCombustible like this

[
 '1' => 'Álcool',
 '2' => 'Gasolina',
 '3' => 'Disel'
]

I hope I’ve helped!

1

When Voce recover the data try to turn it into a list as follows:

$associados = Associado::all()->lists('associado','id');

The list transforms the result into an array with KEY and Value, the first parameter is what you want to appear in Select, and the key will be the value of within select.

How does it look:

<option value="id">associado</option>
  • I tried this way and accused the following error: Badmethodcallexception in Macroable.php line 74: Method lists does not exist.

  • Your class should externder from Eloquent.

  • Got it. This code is in the controller that extends from Controller. In case I should create the method in the model that extends from correct Eloquent?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.