omrakhur omrakhur - 21 days ago 7
HTML Question

Form Model binding in Laravel not preselecting correct option from database in drop down list

I have done data dump on the variable being passed to the view and I know that it has the right piece of data going in. And I have also cross checked it with those drop downs which have their options built into the HTML instead of being passed as an array.
E.g. have a look at the drop down with options inside of the HTML:

<div class="col-sm-7">
{{Form::select('prefix', ['Mr'=>'Mr','Ms'=>'Ms','Mrs'=>'Mrs','Miss'=>'Miss','Dr'=>'Dr','Prof'=>'Prof'],null,['id'=>'prefix','class'=>'select2 select-block-level chzn-select','name' => 'prefix'])}}
</div>


For this drop down, everything works fine. I see the right option pre-selected and I see the options as they are supposed to be. The
$data->prefix
also works fine in lieu of the simple
prefix
as the first arg to the
Form::select
.

But for the drop downs that have an array going in as the second argument to the drop down list like this one:

<div class="col-sm-7">
{{Form::select('team',$data->teams,null, ['id'=>'team','class'=>'select2 select-block-level chzn-select','name'=>'team','required'=>'required'])}}
</div>


...the first option is always selected, no matter what value there is in the database for
$data->team
. Just for the record
$data->teams
and
$data->team
are two different variables. One contains the options and the latter contains the data item for that particular person.
I think the problem is that the keys and values aren't matching...because it works for the first
select
because its options have KV pairs...I don't know..what do you guys think?

Answer

In your case laravel check array key using database field that is stored. If match array key that is kept in select using database value then it is selected automatically. Such as Your array is

`$array=['a' =>name1,'b' => 'name2']`.

If 'a' is stored in database then name1 is selected auto. So please check your array key and database value that is stored