If you have a select box in your form in where user can select multiple options, Here is how you can retain the selected values in the select box in case of validation failure.
Here is the code that you need to append in your option tag
{{in_array($tag->id, old("tags") ?: []) ? "selected": ""}}
This basically means that if the current $tag->id
is in the old('tags')
array then put selected in the option element and if not, don't put anything.
Here is how the final multi-select box.
<label for="name">Tags</label>
<select name="tags[]" class="form-control select-tag" multiple>
@foreach($tags as $tag)
<option value="{{$tag->id}}" {{in_array($tag->id, old("tags") ?: []) ? "selected": ""}}>{{$tag->name}}</option>
@endforeach
</select>
Comments