hendraspt hendraspt - 7 months ago 104
PHP Question

How to set combobox selected value in laravel 5?

I am using laravel 5 and I have an update/edit form which include a combobox on it. But I can't set my combobox value depends on what in the database. Do you know how to do it?


Here is my controller:


public function ubahsurat(Request $request)
{
Surat::where('nomor_surat', '=', $request['nomor_surat'])->update(
['id_jenis_surat' => $request['id_jenis_surat']],

return redirect('/');
}


This is the view:


<div class="col-sm-9">
<select name="id_jenis_surat" class="form-control">
<option></option>
@foreach($jenis_surat as $js)
<option value="{{ $js->id_jenis_surat }}" > {{ $js->jenis_surat }} </option>
@endforeach
</select>
</div>

Answer

You can do like this:

   <div class="col-sm-9">
     <select name="id_jenis_surat" class="form-control">
     <option></option>
        @foreach($jenis_surat as $js) 
        <option value="{{ $js->id_jenis_surat }}" @if($combobox_value_from_database==$js->id_jenis_surat) selected="selected" @endif> {{ $js->jenis_surat }} </option> 
        @endforeach
    </select>

Note: I would encourage you to use Laravel Form Builders. so you can avoid handling these type of issues.

Comments