@mekol take a look at this thread: https://laracasts.com/discuss/channels/general-discussion/select2-tags-old-input-in-laravel
Mar 18, 2020
4
Level 1
Display old multiple select values with select2 jQuery
I am using the select2 jQuery function for my form, when selecting publishers and authors for my book. When I am sending the form, and if I mess up the title and get an error message, I want to still have the values I have selected displayed in the form. I could get it for the normal select box and the checkbox but I can't figure it out for the select2 multiple select boxes.
<div class="form-group">
<label for="publishers">Verlag(e):</label>
<select name="publishers[]" multiple class="form-control select2-multi <!-- @error('publishers') is-invalid @enderror -->">
@foreach ($publishers as $publisher)
<option value="{{ $publisher->id }}">{{ $publisher->name }}</option>
@endforeach
</select>
@error('publishers')
<div class="alert alert-danger">{{ $message }}</div>
@enderror
</div>
Level 53
@mekol this should work:
Plain PHP:
<option
value="{{ $publisher->id }}"
{{ in_array($publisher->id, old('publishers') ?? []) ? 'selected' : '' }}
>
{{ $publisher->name }}
</option>
Using collection:
<option
value="{{ $publisher->id }}"
{{ collect(old('publishers'))->contains($publisher->id) ? 'selected' : '' }}
>
{{ $publisher->name }}
</option>
1 like
Please or to participate in this conversation.