kriszpchicken's avatar

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>
0 likes
4 replies
kriszpchicken's avatar

Thank you! I already tried that, but if I change my code like that I can't get any of my values back.

Sti3bas's avatar
Sti3bas
Best Answer
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.