skip to Main Content

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 class="mb-3">
    <label for="nationality" class="form-label fw-bold">Select<span class="required">*</span></label>
    <select class="form-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?

2

Answers


  1. 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 class="mb-3">
        <label for="nationality" class="form-label fw-bold">Select<span class="required">*</span></label>
        <select class="form-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>
    
    Login or Signup to reply.
  2. <option value="{{$nationality}}" @selected(old('nationality')==$nationality)>
     {{$nationality}}
    </option>
    

    add the @selected directive in blade.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search