Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

m11ad's avatar
Level 1

How to save sortable select2 options ?

Here at my blade file , I'm trying to make this select2 option menu sortable

<select class="form-control select2" name="selected_items[]" multiple="multiple">
    <?php $default = null; ?>
    @if(isset($items))
        @if (! empty($selectedValues))
            @foreach($selectedValues as $selectedVal)
                @foreach($items as $option)
                    @if ( $selectedVal == $option->$itemId )
                        <option value="{{ $option->$itemId }}" selected="selected">{{ $option->$itemTitle }} {{ $option->slug ? '(' . $option->slug. ')' : '' }}</option>
                    @endif
                @endforeach
            @endforeach
            @foreach($items as $option)
                @if ( ! in_array($option->$itemId, $selectedValues) )
                    <option value="{{ $option->$itemId }}">{{ $option->$itemTitle }} {{ $option->slug ? '(' . $option->slug. ')' : '' }}</option>
                @endif
            @endforeach
        @else
            @foreach($items as $option)
                <option value="{{ $option->$itemId }}">{{ $option->$itemTitle }} {{ $option->slug ? '(' . $option->slug. ')' : '' }}</option>
            @endforeach
        @endif
    @endif
</select>

I used the following JS to make it draggable

            var el = document.querySelector('.select2-selection__rendered');
            Sortable.create(el, {})

Right now it's sortable , but it doesn't save. what should I do so when I click on save the reordered values get saved?

0 likes
2 replies
nexxai's avatar

It would probably be a lot easier if you sorted the data before you sent it to your view. Then you could use the usual Eloquent query builder methods to sort the items exactly how you want them before the page ever even has a chance to see them.

Snapey's avatar

what do you get when you post the values back to the server?

Please or to participate in this conversation.