Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting selected option in laravel form

I need to give selected value like this html:

<select name="myselect" id="myselect">
 <option value="1">Item 1</option>
 <option value="2" selected='selected'>Item 2</option>

how can I achieve this, with laravel forms?

like image 773
Min Khant Lu Avatar asked Jul 18 '16 03:07

Min Khant Lu


2 Answers

Everybody talking about you go using {!! Form::select() !!} but, if all you need is to use plain simple HTML.. here is another way to do it.

<select name="myselect">
@foreach ($options as $key => $value)
    <option value="{{ $key }}"
    @if ($key == old('myselect', $model->option))
        selected="selected"
    @endif
    >{{ $value }}</option>
@endforeach
</select>

the old() function is useful when you submit the form and the validation fails. So that, old() returns the previously selected value.

like image 97
lucasvscn Avatar answered Sep 24 '22 08:09

lucasvscn


You can do it like this.

<select class="form-control" name="resoureceName">

  <option>Select Item</option>

  @foreach ($items as $item)
    <option value="{{ $item->id }}" {{ ( $item->id == $existingRecordId) ? 'selected' : '' }}> {{ $item->name }} </option>
  @endforeach    </select>
like image 24
Matiullah Karimi Avatar answered Sep 22 '22 08:09

Matiullah Karimi