mercredi 21 octobre 2020

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="">
  <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) 
         
        @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>


via Chebli Mohamed