Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Lars-Janssen's avatar

Combo box select value from database

I've two values in my combo box. Car and bicycle when the user selects one of them it will be stored in the database with 1 or 2. But how do I make sure that when the user edits it the chosen values shows up.

For example I've saved bicycle in the database than when the user wants to edit it it must show bicycle and not car!

0 likes
3 replies
Komayo's avatar

I think your problem is with the values of combobox Vs database. Your saving 1 for bike 2 for car in database. But when you load them at a combobox or selectbox, default index is zero, 0. So your bike (1 in db) will be 0 in combobox. Car (2 in db) will be 1 ou combobox. So when you load combobox and try to edit bike it will show car. Because car índex in combo = 1 (same as bike in db). Usualy you need to sync the combos and selects boxes while retrieving data from database to fill them. Theres a few tricks. Personally myself i use always a array to sync the data. Because arrays also start at zero. So no issues. :).

wing5wong's avatar

You can use the lists() method on your model to get the text and id.

then you can build the option element and set the value and text using that.

$options = $transport->lists('name','id');

@foreach($options as $id=>$name)
    <option value="{ { $id } }">{ { $name } }</option>
@endforeach
Snapey's avatar

easy if you are using Laravel Collective Form helpers

echo Form::select('transport', array('1' => 'Bike', '2' => 'Car'), $yourData->transport);

A little bit more complicated if you build the option list yourself, but at some point you need to create an array of the options and give them all keys. It does not matter that they are 1 and 2 and not 0 and 1, you can have any string as a key.

Please or to participate in this conversation.