Home > database >  How to get the old value in a select without unchecked with option formed with an foreach
How to get the old value in a select without unchecked with option formed with an foreach

Time:02-01

I need a little help..

In case of validation errors, when the page is reloaded I lose the information entered previously.

This is my code:

Controller:

public function create()
    {
        $nationalities = array('Italian','Brazilian','Spanish','Romanian');
        return view('guest.create', ['nationalities'=>$nationalities);
    }


public function store(Request $request)
    {
        $request->validate([
            'nationality' => 'required'
        ]);

        Guest::create([
            'nationality' => $request->nationality
        ]);

        return redirect(route('guest.index'));
    }

View:

 <div >
    <label for="nationality" >Select<span >*</span></label>
    <select  id="nationality" name="nationality" aria-label="Floating label select example">
        @foreach($nationalities as $nationality)
        <option value="{{$nationality}}">{{$nationality}}</option>
        @endforeach
    </select>
</div>

How can I modify the code so that this doesn't happen?

CodePudding user response:

How can you select back what failed if you did not even ask for the old value?

This may or not work depending on how you are validating, but you did not want to show that...

<div >
    <label for="nationality" >Select<span >*</span></label>
    <select  id="nationality" name="nationality" aria-label="Floating label select example">
        @foreach($nationalities as $nationality)
            <option value="{{$nationality}}" {{ old('nationality') === $nationality) ? 'selected="selected"' : '' }}>{{$nationality}}</option>
        @endforeach
    </select>
</div>

CodePudding user response:

<option value="{{$nationality}}" @selected(old('nationality')==$nationality)>
 {{$nationality}}
</option>

add the @selected directive in blade.

  • Related