spatie/eloquent-sortable
Add sortable behavior to Laravel Eloquent models via a trait. Automatically sets an order column on create (max + 1) and provides a scope to retrieve records in the correct order. Ideal for drag-and-drop lists and custom ordering.
Install the package via Composer, then implement the Sortable interface and SortableTrait in any Eloquent model that needs reordering capability. Start by adding a migration to include an order_column integer column (or use the default name). The package works out-of-the-box: new records automatically get the next order_column value, and MyModel::ordered()->get() retrieves them sorted. First real-world use case: managing sorted lists like navigation menu items or FAQ entries where item position matters.
order_column; save() assigns increasing numbers automatically.setNewOrder([1, 3, 2]) with model IDs to instantly reorder all items (e.g., after a drag-and-drop UI update).moveOrderUp(), moveOrderDown(), moveToStart(), moveToEnd() for user-triggered single-item adjustments.buildSortQuery() to scope ordering to a foreign key like user_id, enabling separate sort orders per user (e.g., per-user custom todo lists).setNewOrderByCustomColumn('uuid', [...]) for APIs where clients use UUIDs instead of DB IDs.EloquentModelSortedEvent to purge caches or sync排序 state (e.g., via queue jobs).setNewOrder() in a transaction.ignore_timestamps config option is critical when you want to avoid noise in updated_at (e.g., for audit trails), especially for high-frequency reorder operations.order_column is excluded from orderBy to prevent ordering issues; use withoutTrashed() or a custom buildSortQuery.moveAfter() and moveBefore() fire model events (Laravel 10+), so test your event listeners for side effects—don’t assume they’re quiet.save() in your model, call parent::save($options) to ensure the trait’s ordering logic (like auto-increment on create) still runs.buildSortQuery() must be static and return a query builder—common mistake: using $this or returning a collection.How can I help you explore Laravel packages today?