Drag and drop
Lets users reorder items by dragging and dropping them. It uses the Alpine Sort plugin that ships with Livewire 4; if a handler is given, the new order is sent to the server.
Basic usage
Each row is an acun:sortable.item and needs a unique key. A row is dragged by grabbing it anywhere. Without handler, the new order stays in the browser only; when the page is reloaded, the old order returns.
<acun:sortable>
<acun:sortable.item key="1">Electronics</acun:sortable.item>
<acun:sortable.item key="2">Home and living</acun:sortable.item>
<acun:sortable.item key="3">Clothing</acun:sortable.item>
<acun:sortable.item key="4">Beauty</acun:sortable.item>
</acun:sortable>
| Prop | Values |
|---|---|
key | Item identifier, e.g. the record id |
Dragging by the handle
With handle, dragging starts only from the handle icon on the left, and the cursor changes only there. When a row contains buttons or links, this keeps the row from shifting by accident while you use them. To spread the content across the row, give the slot a flex container.
<acun:sortable handle>
<acun:sortable.item key="1"><span class="flex items-center justify-between gap-3">Electronics <acun:button size="sm" variant="ghost">Edit</acun:button></span></acun:sortable.item>
<acun:sortable.item key="2"><span class="flex items-center justify-between gap-3">Home and living <acun:button size="sm" variant="ghost">Edit</acun:button></span></acun:sortable.item>
<acun:sortable.item key="3"><span class="flex items-center justify-between gap-3">Clothing <acun:button size="sm" variant="ghost">Edit</acun:button></span></acun:sortable.item>
</acun:sortable>
| Prop | Values |
|---|---|
handle | true | false |
Saving with Livewire
handler is the name of a Livewire method; the key of the dropped item and its new zero-based position are sent to this method. Remember to give wire:key in loops.
<acun:sortable handler="updateOrder">
@foreach ($categories as $category)
<acun:sortable.item :key="$category->id" wire:key="category-{{ $category->id }}">{{ $category->name }}</acun:sortable.item>
@endforeach
</acun:sortable>
| Prop | Values |
|---|---|
handler | Livewire method name |
Server method
The method receives the item's key and its new position. Because the records in between shift as well, renumbering the whole list is the safest approach.
public function updateOrder(int $categoryId, int $newPosition): void
{
$order = Category::orderBy('position')->pluck('id')
->reject(fn (int $id) => $id === $categoryId)
->values();
$order->splice($newPosition, 0, [$categoryId]);
foreach ($order as $position => $id) {
Category::whereKey($id)->update(['position' => $position]);
}
}
Props and slots
The values the component accepts.
| Prop | Default | Description |
|---|---|---|
handler | null | Livewire method; called with (key, new position) |
handle | false | true: dragged only by the handle icon; false: by the whole row |
sortable.item: key | — | Required; item identifier |