Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define the selected option with the old input in Laravel / Blade

I have this code:

<select required="required" class="form-control" name="title">
    <option></option>
    @foreach ($titles as $key => $val)
        @if (stristr($key, 'isGroup'))
            <optgroup label="{{ $val }}">
        @else
        <option value="{{ $key }}">{{ $val }}</option>
        @endif
    @endforeach
    </select>

So when the form have errors i use the line Redirect::route('xpto')->withInput()->withErrors($v). But i can't re-populate the select fields. Any way to do this without using JavaScript for example?

like image 844
Christopher Avatar asked Mar 19 '15 15:03

Christopher


2 Answers

Also, you can use the ? operator to avoid having to use @if @else @endif syntax. Change:

@if (Input::old('title') == $key)
      <option value="{{ $key }}" selected>{{ $val }}</option>
@else
      <option value="{{ $key }}">{{ $val }}</option>
@endif

Simply to:

<option value="{{ $key }}" {{ (Input::old("title") == $key ? "selected":"") }}>{{ $val }}</option>
like image 73
Tim Lewis Avatar answered Nov 02 '22 19:11

Tim Lewis


Instead of using Input class you can also use old() helper to make this even shorter.

<option {{ old('name') == $key ? "selected" : "" }} value="{{ $value }}">
like image 31
5less Avatar answered Nov 02 '22 19:11

5less