Fix sort_order: sequential 1,2,3 + renormalize after every save

- saving: always shift >= new position by +1 (no conflict check needed)
- saved: renormalize all records to 1, 2, 3... via direct DB update
  (no model events triggered) to close any gaps left by the move
- Migration updated to use step 1 instead of 10

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-09-08 06:59:14 +00:00
parent 2e082d4aad
commit 5610282078
2 changed files with 19 additions and 13 deletions
+18 -12
View File
@@ -5,6 +5,7 @@ namespace App\Models\Tenant;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Scopes\TenantScope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class LaborCategory extends Model
{
@@ -16,26 +17,31 @@ class LaborCategory extends Model
{
parent::boot();
// When sort_order is changed to a value already occupied by another record,
// shift all records at that position and above up by 1 to make room.
static::saving(function (self $cat) {
$new = (int) $cat->sort_order;
$old = (int) ($cat->getOriginal('sort_order') ?? PHP_INT_MAX);
if ($new === $old) return;
$conflict = static::withoutGlobalScope(TenantScope::class)
// Make room: shift all records at >= new position up by 1.
static::withoutGlobalScope(TenantScope::class)
->where('company_id', $cat->company_id)
->where('sort_order', $new)
->where('sort_order', '>=', $new)
->where('id', '!=', $cat->id ?? 0)
->exists();
->increment('sort_order');
});
if ($conflict) {
static::withoutGlobalScope(TenantScope::class)
->where('company_id', $cat->company_id)
->where('sort_order', '>=', $new)
->where('id', '!=', $cat->id ?? 0)
->increment('sort_order', 10);
static::saved(function (self $cat) {
// Renormalize to 1, 2, 3, … to close any gaps left after the move.
$ids = static::withoutGlobalScope(TenantScope::class)
->where('company_id', $cat->company_id)
->orderBy('sort_order')
->orderBy('id')
->pluck('id');
foreach ($ids as $i => $id) {
DB::table('labor_categories')
->where('id', $id)
->update(['sort_order' => $i + 1]);
}
});
}