[laravel] 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?

This question is related to laravel laravel-4 blade

The answer is


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

My solution here is to loop, just to avoid duplicate option

                            <select class="form-control" name="status" >
                              <?php $lists = ['Current', 'Win', 'Lose']; ?>

                              @foreach($lists as $list)
                              <option value={{$list}} {{(old('status') == $list?'selected':'')}} >{{$list}}</option>
                              @endforeach

                            </select>

Okay, my 2 cents, using the default value of Laravel's old() function.

<select name="type">
    @foreach($options as $key => $text)
        <option @if((int) old('type', $selectedOption) === $key) selected @endif value="{{ $key }}">{{ $text }}</option>
    @endforeach
</select>

<select name="gender" class="form-control" id="gender">
                                <option value="">Select Gender</option>
                                <option value="M" @if (old('gender') == "M") {{ 'selected' }} @endif>Male</option>
                                <option value="F" @if (old('gender') == "F") {{ 'selected' }} @endif>Female</option>
                            </select>

      <select class="form-control" name="kategori_id">
        <option value="">-- PILIH --</option>
        @foreach($kategori as $id => $nama)
            @if(old('kategori_id', $produk->kategori_id) == $id )
            <option value="{{ $id }}" selected>{{ $nama }}</option>
            @else
            <option value="{{ $id }}">{{ $nama }}</option>
            @endif
        @endforeach
        </select>

this will help you , just compare with old if exist , if not then compare with the default value

<select name="select_name">
    @foreach($options as $key => $text)
       <option {{ ($key == old('select_name',$default))?'selected':'' }}> {{ $text }} </option>
    @endforeach
</select>

the $default is the value that injected from the controller to the view


After Playing around a bit I came up with this and it seems to work just splendidly

<select name="options[]" id="options" class="form-control" multiple>
    @foreach($settings->includes->get('optionList') as $option)
        <option value="{{ $option->id }}" {{ (collect(old('options'))->contains($option->id)) ? 'selected':'' }}>{{ $option->name }}</option>
    @endforeach
</select>

I may be 100% wrong in leveraging the collect function but it works fine on many of my tests. After seeing a few other posts on the site I saw someone recommend leveraging the in_array($needle, $array) function but after noticing that if my old('options') was null it would error out because it requires in_array requires, bet you guessed an array. So after finding the solution to that albeit ugly solution I played with the collect method because after all we are using larval right! well anyway the ugly solution is as follows

@if (old("options")){{ (in_array($option->id, old("options")) ? "selected":"") }}@endif

inline but man that looks ugly to me so long story short I am using the following instead

{{ (collect(old('options'))->contains($option->id)) ? 'selected':'' }}

Hope this helps others!!

This does not seem to work for a non multiple select field ill get back with one that does work for that though.


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>

I have changed the code to include '' on the title value since without the quotes it fails to work

    <select class="form-control" name="team" id="team">
     <option value="">---------Choose Team---------</option>
           @foreach($teams as $team)
    <option value="{{$team->id}}" {{(old('team')==$team->id)? 'selected':''}}>{{$team->name}}</option>

    @endforeach
    </select>

    eg.<select name="title">
    <option value="1"  {{ old('title') == '1' ? 'selected' : '' }}>
        Item 1
    </option>
    <option value="2" {{ old('title') == '2' ? 'selected' : '' }}>
        Item 2
    </option>

    </select>

<select style="width: 100%;" name="id_driver" id="id_driver" >
  <option value="" @if (old('id_driver') == "")  selected @endif>Select</option>
  @foreach(\App\Driver::all() as $driver)
    <option value="{{$driver->id}}" @if (old('id_driver') == $driver->id)  
        selected  @endif >(#{{$driver->id}}) {{$driver->business_name}}
    </option>
  @endforeach
</select>

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

<option {{ old('name') == $key ? "selected" : "" }} value="{{ $value }}">

Laravel 6 or above: just use the old() function for instance @if (old('cat')==$cat->id), it will do the rest of the work for you.

How its works: select tag store the selected option value into its name attribute in bellow case if you select any option it will store into cat. At the first time when page loaded there is nothing inside cat, when user chose a option the value of that selected option is stored into cat so when user were redirected old() function pull the previous value from cat.

 {!!Form::open(['action'=>'CategoryController@storecat', 'method'=>'POST']) !!}
        <div class="form-group">
            <select name="cat" id="cat" class="form-control input-lg">
                <option value="">Select App</option>
                @foreach ($cats as $cat)
                    @if (old('cat')==$cat->id)
                        <option value={{$cat->id}} selected>{{ $cat->title }}</option>
                    @else
                        <option value={{$cat->id}} >{{ $cat->title }}</option>
                    @endif
                @endforeach
            </select>
        </div>

        <div class="from-group">
            {{Form::label('name','Category name:')}}
            {{Form::text('name','',['class'=>'form-control', 'placeholder'=>'Category name'])}}
        </div>
    <br>
    {!!Form::submit('Submit', ['class'=>'btn btn-primary'])!!}
    {!!Form::close()!!}

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

Considering user also want to edit their previous input,

<select name="title">
  @foreach ($titles as $key => $value)
    <option value="{{$value->id}}" {{(old('title', $user->title_id) == $value->id ? 'selected' : '')}} > {{$value->name}} </option>
  @endforeach
</select>

old('title', $user->title_id) returns user saved title_id first time, if validation fails it returns user-selected title_id. Then if it is match with current option id, it is being selected.


Examples related to laravel

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration Target class controller does not exist - Laravel 8 Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required How can I run specific migration in laravel Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

Examples related to laravel-4

Parameter binding on left joins with array in Laravel Query Builder Laravel 4 with Sentry 2 add user to a group on Registration 'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel Can I do Model->where('id', ARRAY) multiple where conditions? how to fix stream_socket_enable_crypto(): SSL operation failed with code 1 Rollback one specific migration in Laravel How can I resolve "Your requirements could not be resolved to an installable set of packages" error? Define the selected option with the old input in Laravel / Blade Redirect to external URL with return in laravel laravel the requested url was not found on this server

Examples related to blade

How to access URL segment(s) in blade in Laravel 5? Lumen: get URL parameter in a Blade view Laravel: How do I parse this json data in view blade? Switch in Laravel 5 - Blade Laravel-5 how to populate select box from database with id value and name value Laravel 5: Display HTML with Blade Define the selected option with the old input in Laravel / Blade Laravel 5 call a model function in a blade view Displaying the Error Messages in Laravel after being Redirected from controller How to include a sub-view in Blade templates?