Laravel PHP · Inline✓ Human-reviewed

Tenant-safe ordered lists in Laravel PHP

Replace the sortable trait's used slice with explicit list ordering and atomic full-list reordering, with parent-row locking, membership checks, and rollback tests.

Approved 2026-12-04T12:03:47.372656Z · Submission 20

Tenant-safe ordered lists in Laravel PHP

Pinned source and scope

Reference: Spatie's MIT-licensed spatie/eloquent-sortable 5.0.1 at caf2596e5df0260d0e2863e89b750611eef2fc59. Read src/SortableTrait.php, src/Sortable.php, src/EloquentModelSortedEvent.php, configuration, and ordering tests. Retain the MIT notice if adapting source. Framework baseline: Laravel PHP 1b57d01aa866b042a75683bd9ef3517008c632fc; inspect your installed version before implementation.

Replace one list's automatic append, ordered read, and full-list reorder. Exclude arbitrary custom primary keys, relative move/swap APIs, and cross-list moves unless callers need them. This guidance has not been exercised in your app; in particular, concurrency needs the production database, not a sequential SQLite-only test.

What the PHP trait actually does

The creating hook appends at scoped maximum plus one when configured. ordered() sorts the configured order column. setNewOrder() assigns consecutive values in input order, removes the soft-delete global scope for those updates, optionally ignores timestamps, and dispatches EloquentModelSortedEvent. buildSortQuery() controls list membership for several operations. The source's assignment loop itself is not an authorization check or an atomic reorder transaction.

Inventory SortableTrait, ordered, setNewOrder, move/swap calls, customized buildSortQuery, custom key/position columns, timestamps, and event listeners. Explicitly decide whether deleted members participate. The implementation below strengthens serialization and membership checking; it is not an accidental promise of identical event/soft-delete behavior.

Application-owned write path

  1. Keep the existing position column and data. A (list_id, position, id) index helps ordered reads; do not renumber production data or change constraints as part of blindly removing a trait.
  2. Put append and reorder in the list's existing action/service. Authorize the parent list and apply tenant ownership. Every append, delete, restore, cross-list transfer, and reorder that changes membership/order must follow the same parent-lock protocol; locking only the reorder endpoint is insufficient.
  3. Inside DB::transaction, select the authorized parent row with lockForUpdate() before reading children. This serializes even an empty list on PostgreSQL/MySQL. Recheck any mutable authorization under that lock. SQLite does not provide equivalent row-level FOR UPDATE semantics; test the target driver's write-transaction behavior separately.
  4. Under the lock, read the current member IDs. Validate the supplied IDs as a bounded list of distinct positive IDs whose set exactly equals current membership. Reject foreign-tenant IDs, omissions, duplicates, and unknown/deleted IDs according to the explicit policy. Do not partially reorder while validation is still running.
  5. Apply ranks 1 through N in the supplied order, always constraining each update to the authorized parent. Compare affected rows to expectations. All writes and any version check belong to the same transaction. If existing code has an immediate unique (list_id, position) constraint, a swap can fail midway: use a checked temporary disjoint rank range before final assignment, or an explicitly reviewed deferrable-constraint design. Do not drop a constraint merely to make the example pass.
  6. For append, lock that same parent before computing scoped max(position) + 1. Check integer limits. For reads, use orderBy('position')->orderBy('id'). Decide whether gaps after deletion are acceptable; contiguous numbering is only guaranteed by a successful full reorder.
  7. Preserve the used timestamp behavior and listeners deliberately. Dispatch the app's sorted notification only after commit; never announce a rolled-back order. If retaining the package event class would prevent uninstalling it, migrate listeners to an app-owned event in the same change.

Illustrative core, after the lock, authorization, full membership check, and any unique-rank staging have succeeded:

foreach ($orderedIds as $index => $id) {
    $list->items()->whereKey($id)->update(['position' => $index + 1]);
}

This fragment alone is intentionally not a safe reorder handler. Bulk query updates do not automatically reproduce per-model hooks; account for those if your app relies on them.

Trial cases that catch unsafe replacements

  • List A has IDs [11, 24, 39], list B has [50]. Reorder A to [39, 11, 24]; assert exact returned/read IDs and positions, with B unchanged.
  • Send [39, 39, 24], [39, 11], and [39, 11, 50]; each fails with no changed positions or events.
  • Inject a database error on the second update; confirm all positions roll back and no after-commit notification is delivered.
  • Run two reorders, and a reorder versus append/delete, concurrently over independent production-driver connections. The result must be one complete serial outcome, not mixed positions or lost members.
  • Cover empty list append, first/last member behavior, soft-deleted membership/restore, existing duplicate positions, unique-rank constraints, and retained timestamp policy.

Run the target app's ordering feature tests with php artisan test --filter=Reorder, then a real-database concurrency test. Compare the declared slice against the package-backed implementation. Inventory every remaining trait/event reference and run composer why spatie/eloquent-sortable before uninstalling. Record compatibility differences and test evidence with the change.