Define the selected option with the old input in Laravel / Blade
Asked Answered
R

22

66

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?

Rushing answered 19/3, 2015 at 15:11 Comment(0)
R
33

The solution is to compare Input::old() with the $keyvariable using Blade Directives - If Statements.

@if (Input::old('title') == $key)
    <option value="{{ $key }}" selected>{{ $val }}</option>
@else
    <option value="{{ $key }}">{{ $val }}</option>
@endif
Rushing answered 19/3, 2015 at 15:16 Comment(8)
I was gonna ask if this was the problem. There's a difference between "repopulate the select" and "show selected option". Try to explain you issue more clearly in the future.Winch
Repopulate the select with the selected option.Rushing
I know, and I'm glad you got it working, but your title and the description of your problem are somewhat conflicting.Winch
I think that's okay now :)Rushing
@Rushing What about the input name be array like this title[] what we should? I do the same thing it is not working.Soulsearching
You could do something like this: @php($titleArray = old('title))@endphp @if ($titleArray['any_key'] == $key)Purdy
This code is too redundant. I would rather accept Tim Lewis answer instead your own.Hervey
this is better answer to this question #35612445Riancho
W
96

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>
Winch answered 19/3, 2015 at 15:25 Comment(1)
I still get a lot of upvotes/activity on this answer, which is appreciated, but be sure to look at https://mcmap.net/q/294698/-define-the-selected-option-with-the-old-input-in-laravel-blade too, as Laravel has added this as an @selected (and @checked for checkboxes/radio) Blade Directive in Laravel 9.x (and above).Winch
A
37

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

<option {{ old('name') == $key ? "selected" : "" }} value="{{ $value }}">
Analphabetic answered 16/1, 2018 at 19:49 Comment(0)
R
33

The solution is to compare Input::old() with the $keyvariable using Blade Directives - If Statements.

@if (Input::old('title') == $key)
    <option value="{{ $key }}" selected>{{ $val }}</option>
@else
    <option value="{{ $key }}">{{ $val }}</option>
@endif
Rushing answered 19/3, 2015 at 15:16 Comment(8)
I was gonna ask if this was the problem. There's a difference between "repopulate the select" and "show selected option". Try to explain you issue more clearly in the future.Winch
Repopulate the select with the selected option.Rushing
I know, and I'm glad you got it working, but your title and the description of your problem are somewhat conflicting.Winch
I think that's okay now :)Rushing
@Rushing What about the input name be array like this title[] what we should? I do the same thing it is not working.Soulsearching
You could do something like this: @php($titleArray = old('title))@endphp @if ($titleArray['any_key'] == $key)Purdy
This code is too redundant. I would rather accept Tim Lewis answer instead your own.Hervey
this is better answer to this question #35612445Riancho
A
22

Of all the methods shown to you, I do not recommend using them if your project is made in a version higher than Laravel 9.

use this as laravel itself has added this

Checked / Selected / Disabled

<select name="version">
    @foreach ($product->versions as $version)
        <option value="{{ $version }}" @selected(old('version') == $version)>
            {{ $version }}
        </option>
    @endforeach
</select>
Another answered 26/4, 2022 at 12:27 Comment(0)
C
14
<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>
Crunch answered 30/11, 2017 at 7:40 Comment(3)
While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply.Arlie
For some reason, the ternary operator doesn't work for me, and this did the job.Cory
Works as expected !Tabaret
S
10

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.

Scholem answered 4/10, 2016 at 18:6 Comment(0)
I
8

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>
Interrex answered 12/12, 2017 at 6:33 Comment(0)
R
5

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()!!}
Rieth answered 1/2, 2020 at 18:10 Comment(0)
I
2
<option value="{{ $key }}" {{ Input::old('title') == $key ? 'selected="selected"' : '' }}>{{ $val }}</option>
Indre answered 22/5, 2017 at 19:55 Comment(0)
A
2
      <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>
Areca answered 20/4, 2018 at 10:53 Comment(0)
R
2

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

Richard answered 16/3, 2020 at 8:0 Comment(1)
@RJFares you can use the $default only if there is no old('select_name')Richard
M
2

Short and clean usage example for Laravel 8.59.0 (pre selected edit form with old)

You can use it for your edit page. It comes with the default selection from the database and if you submit an did not pass verification form, the answer is returned by including the old.

<select name="brand_id">
    @foreach ($brands as $brand)
        <option value="{{ $brand->id }}" @if ($product->brand_id === $brand->id || old('brand_id') === $brand->id) selected @endif>{{ $brand->title }}</option>
    @endforeach
</select>
Mogador answered 8/9, 2021 at 12:38 Comment(0)
B
1

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>
Barbette answered 5/10, 2017 at 13:14 Comment(0)
B
1

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>
Bromic answered 7/2, 2018 at 9:47 Comment(0)
D
1
<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>
Dissimilate answered 5/10, 2020 at 16:14 Comment(0)
W
1

Many answers demonstrating one liners using ternary operators, but I think using @if is more readable, at least for beginners. The following would have sufficed without the else statement.

 <option value="{{ $key }}" @if(old('title')===$key) selected @endif>{{ $val }}</option>
Winniewinnifred answered 25/8, 2021 at 16:41 Comment(1)
I totally agree with you but I think you should use equal operator(==) instead of identical(===) for it to work!Kenning
M
1

As of Laravel 9, the method I follow is

If options are hardcoded in view:

<option value="male" {{old('gender', $customer['gender']) === 'male' ? "selected" : ''}}> Male </option>

If options are passed down from controller as array:

@foreach ($genders as $gender)
    <option value="{{$gender}}" {{ old('gender', $customer['gender']) === $gender ? "selected='selected'" : '' }}> {{ucwords($gender)}} </option>
@endforeach

PS: Took the liberty to consider an example of customer model and gender property.

Milliary answered 17/7, 2022 at 8:47 Comment(0)
S
1

For Laravel 9, you can use this one as example. I think this one is worked.

<select name="version_id" class="form-control custom-select">
    <option value="">Select Version</option>
    @foreach($versions as $version)
        <option value="{{ $version->id }}" {{ old('version_id', $apps->version_id) == $version->id ? 'selected' : null}}>{{ $version->name }}</option>
    @endforeach
</select>

This may be useful for dropdowns in laravel, if you want edit data, but when you click edit, the old data is selected rather than nothing.

Slider answered 25/7, 2022 at 7:4 Comment(0)
A
0
<select>
    @if(old('value') =={{$key}})
     <option value="value" selected>{{$value}}</option>
    @else
     <option value="value">{{$value}}</option>
    @endif
</select>
Abana answered 20/10, 2017 at 7:0 Comment(1)
This feels a bit overhead as you can use {{ old('foo') == $foo->foo_id ? ' selected="selected' : '' }} instead. And please always set a value for your tag attributes!Scopophilia
P
0

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.

Pussyfoot answered 23/12, 2020 at 7:11 Comment(0)
A
0

Improving CodeToLife's answer with error validation implementation like below

<div class="form-group row">
    <label for="person-field" class="col-md-4 col-form-label text-right">First Person</label>
    <div class="col-md-6">
        <select id="person-field" class="custom-select select2 @error('person') is-invalid @enderror" name="person" required>
            <option></option>
            @foreach(\App\User::all() as $user)
                <option value="{{$user->id}}" @if (old('person') == $user->id) selected  @endif>{{$user->name}}
                </option>
            @endforeach
        </select>
        @error('person')
        <span class="invalid-feedback" role="alert">
            <strong>{{ $message }}</strong>
        </span>
        @enderror
    </div>
</div>
Aubergine answered 10/2, 2022 at 8:11 Comment(0)
K
0

A lot more typing, but very clear. I use this in classes to demonstrate how it works. Not recommended for production.

    @if (old('typeid'))
        @if ($type->id == old('typeid'))
            <option value="{{ $type->id }}" selected>
        @else
            <option value="{{ $type->id }}">
        @endif
    @else
        @if ($type->id == $event->typeid)
            <option value="{{ $type->id }}" selected>
        @else
            <option value="{{ $type->id }}">
        @endif
    @endif
Koa answered 26/7, 2022 at 15:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.