Skip to content
Advertisement

Saving selected option after validation in Laravel

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>

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement