3

I need help with saving a selected option after validation fails.

Here is main.blade.php

<form method="POST" action="{{ url('/main') }}">
  <select id="searchEngine" name="searchEngine">
    <option value="google">Google</option>
    <option value="bing">Bing</option>
    <option value="duckduck">DuckDuckGo</option>
  </select>

  @if ($errors->has('searchEngine'))
    <div style="background-color: #faa;">
        @foreach ($errors->all() as $error) 
        {{ $error }} 
        @endforeach
    </div>
  @endif
</form>

Controller looks like:

request()->validate(
            ['searchEngine' => "required|in:google,duckduck"],
            ['searchEngine.in' => $searchEngine.' not working, try another']
        );

I tried this, but it always returns only the last option:

<option value="google" {!! $errors->has('searchEngine') ? 'selected' : '' !!}>Google</option>
<option value="bing" {!! $errors->has('searchEngine') ? 'selected' : '' !!}>Bing</option>
<option value="duckduck" {!! $errors->has('searchEngine') ? 'selected' : '' !!}>DuckDuckGo</option>

1 Answer 1

4

If I understood you correctly you want to keep the previously selected option selected when the validation fails.

<select id="searchEngine" name="searchEngine">
    <option value="google" {{ old('searchEngine') == 'google' ? 'selected' : '' }}>Google</option>
    <option value="bing" {{ old('searchEngine') == 'bing' ? 'selected' : '' }}>Bing</option>
    <option value="duckduck" {{ old('searchEngine') == 'duckduck' ? 'selected' : '' }}>DuckDuckGo</option>
</select>

Less repetitive solution with a @foreach:

<select id="searchEngine" name="searchEngine">
    @foreach(['google' => 'Google', 'bing' => 'Bing', 'duckduck' => 'DuckDuckGo'] as $key => $value)
        <option value="{{ $key }}" {{ old('searchEngine') === $key ? 'selected' : '' }}>{{ $value }}</option>
    @endforeach
</select>
Sign up to request clarification or add additional context in comments.

1 Comment

thank you! You understood me correctly. I also tried to make it with @foreach but didn't succeed. Now I know where I made a mistake. Thank you once again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.