Trung bình Laravel

Những cái bẫy của soft delete trong Laravel: unique index, withTrashed, cascade, restore và prune

Soft delete giấu dòng khỏi Eloquent chứ không giấu khỏi database. Sửa unique index, relationship ra null, cascade bị thiếu, restore thiếu an toàn và dữ liệu giữ mãi.

21 Th11, 2026 10 phút Cập nhật 23 Th10, 2026 6 Khối code
Sơ đồ
graph LR A[Dòng đang active] -->|delete| B[Trashed: đã set deleted_at] B -->|restore| A B -->|hết thời gian lưu giữ| C[Bị prune bởi job định kỳ] A -->|forceDelete| D[Biến mất khỏi database] C --> D

Một khách hàng xóa tài khoản hồi tháng Ba. Qua tháng Năm chị quay lại, đăng ký bằng đúng email cũ. Form báo "The email has already been taken", trong khi trang admin không hề thấy user nào như vậy. Team support "sửa" bằng cách cho validation bỏ qua mấy dòng đã trashed, và giờ đăng ký crash luôn với SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry, vì unique index trên users.email vẫn thấy dòng bị soft delete. Cũng tuần đó, trang đơn hàng bắt đầu ném Attempt to read property "name" on null cho mọi đơn của khách đã đóng tài khoản.

Soft delete nhìn qua tưởng chỉ là tính năng một dòng: thêm use SoftDeletes, thêm cột deleted_at, xong. Thực tế nó đổi luôn ý nghĩa của chữ "tồn tại" trên toàn bộ schema, mà database thì không hề biết chuyện đó. Unique constraint, foreign key, cascade, relationship và raw query vẫn coi dòng bị soft delete là còn sống nhăn. Bài này đi qua từng cái bẫy và mấy pattern đứng vững được trên production.

Soft delete thật ra hoạt động ra sao

Trait SoftDeletes làm đúng hai việc. delete() chạy UPDATE ... SET deleted_at = now() thay vì DELETE, và một global scope gắn thêm WHERE deleted_at IS NULL vô mọi query Eloquent của model đó. Hết. Mọi thứ còn lại đều suy ra từ hai điều này:

  • withTrashed() gỡ scope ra, onlyTrashed() lật nó thành deleted_at IS NOT NULL.
  • restore() set deleted_at về NULL; forceDelete() chạy DELETE thật.
  • $model->trashed() cho biết instance đó đã bị soft delete chưa.
  • Scope chỉ sống trong Eloquent. DB::table('users'), raw SQL, view của database, tool làm báo cáo và cả constraint của database đều thấy mọi dòng.

Vậy là database nghĩ user bị soft delete vẫn còn, còn app thì nghĩ là không. Mọi bug bên dưới đều sinh ra từ chỗ lệch pha này.

Vòng đời của một dòng bị soft delete

graph LR A[Dòng đang active] -->|delete| B[Trashed: đã set deleted_at] B -->|restore| A B -->|hết thời gian lưu giữ| C[Bị prune bởi job định kỳ] A -->|forceDelete| D[Biến mất khỏi database] C --> D

Một dòng không nên nằm ở trạng thái trashed mãi mãi. Quyết định từ đầu là dữ liệu trashed được giữ bao lâu (để undo, để audit hay vì lý do pháp lý), rồi prune sau khoảng đó. Không thì tài khoản "đã xóa" vẫn giữ dữ liệu cá nhân vô thời hạn, bản thân chuyện đó đã là vấn đề tuân thủ.

Unique index đụng độ deleted_at

Bug đăng ký có hai nửa: validation và index. Rule unique:users,email thường là một query thẳng xuống database, nên nó đếm luôn dòng trashed. Còn unique index thường trên email thì chặn dòng thứ hai trùng email, trashed hay không cũng vậy.

Cách sửa nghe hấp dẫn là unique index ghép trên (email, deleted_at). Nó không chạy: trên cả MySQL lẫn PostgreSQL, các giá trị NULL được coi là khác nhau trong unique index, nên hai dòng active trùng email (cùng deleted_at IS NULL) vẫn lọt qua. Vậy là đổi một bug lấy một bug tệ hơn.

Cái mình cần là "unique giữa các dòng active". Trên PostgreSQL đó là partial index. Trên MySQL, xài một generated column bằng NULL với dòng trashed, rồi đặt unique index lên nó; nhiều giá trị NULL được phép trùng, nên dòng trashed không bao giờ đụng nhau.

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropUnique(['email']);
        });

        if (DB::getDriverName() === 'pgsql') {
            DB::statement('CREATE UNIQUE INDEX users_email_active_unique ON users (email) WHERE deleted_at IS NULL');

            return;
        }

        Schema::table('users', function (Blueprint $table) {
            $table->string('active_email')->nullable()->virtualAs('IF(deleted_at IS NULL, email, NULL)');
            $table->unique('active_email', 'users_email_active_unique');
        });
    }

    public function down(): void
    {
        if (DB::getDriverName() === 'pgsql') {
            DB::statement('DROP INDEX users_email_active_unique');
        } else {
            Schema::table('users', function (Blueprint $table) {
                $table->dropUnique('users_email_active_unique');
                $table->dropColumn('active_email');
            });
        }

        Schema::table('users', function (Blueprint $table) {
            $table->unique('email');
        });
    }
};

Sau đó chỉnh validation cho khớp với index: Rule::unique('users', 'email')->withoutTrashed() chỉ đếm dòng có deleted_at là null. Validation cho user một thông báo dễ hiểu; còn index mới là thứ thật sự đảm bảo đúng khi có nhiều lượt đăng ký chạy song song. Phải có cả hai.

Relationship trỏ tới dòng đã trashed

Soft delete một khách hàng không đụng gì tới đơn hàng của họ. $order->customer chạy một query Eloquent, global scope giấu khách hàng đã trashed, và mình nhận về null. View nào làm $order->customer->name là crash.

Quyết định theo từng relationship, coi nghiệp vụ muốn gì. Với dữ liệu lịch sử như đơn hàng, hóa đơn, audit log, record liên quan vẫn phải thấy được, nên cho relationship lấy luôn dòng trashed:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Order extends Model
{
    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class)->withTrashed();
    }
}

Với màn hình admin mở record đã trashed bằng URL, route model binding mặc định trả 404. Bật riêng cho từng route bằng Route::get('/admin/customers/{customer}', ShowCustomer::class)->withTrashed();. Còn trong Blade, hiện rõ trạng thái (@if ($order->customer->trashed())) thay vì giả bộ như khách hàng vẫn đang active.

Cascade khi soft delete (và khi restore)

ON DELETE CASCADE trên foreign key chỉ chạy khi có DELETE. Soft delete là UPDATE, nên database không cascade gì hết. Nếu xóa project cũng phải ẩn luôn task của nó, mình phải tự làm trong app, và làm ngược lại khi restore.

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Project extends Model
{
    use SoftDeletes;

    public function tasks(): HasMany
    {
        return $this->hasMany(Task::class);
    }

    protected static function booted(): void
    {
        static::deleted(function (Project $project): void {
            if ($project->isForceDeleting()) {
                return;
            }

            $project->tasks()->each(fn (Task $task) => $task->delete());
        });

        static::restoring(function (Project $project): void {
            $project->tasks()
                ->onlyTrashed()
                ->where('deleted_at', '>=', $project->deleted_at)
                ->each(fn (Task $task) => $task->restore());
        });
    }
}

Có ba chi tiết làm đoạn này đúng thiệt chứ không chỉ nhìn có vẻ đúng. Cascade chạy trong deleted (sau khi project đã có timestamp), nên timestamp của task không bao giờ sớm hơn của project. Restore chỉ đem lại task bị trashed cùng lúc hoặc sau project, nên task mà user cố ý xóa từ tháng trước vẫn nằm yên đó. Và khi forceDelete thì bỏ qua vòng lặp, vì foreign key cascade thật sẽ lo. Xóa từng model một sẽ bắn event cho từng task, đúng thứ mình cần nếu task còn cascade tiếp; với số lượng con rất lớn, một câu update(['deleted_at' => now()]) nhanh hơn nhưng bỏ qua event của tụi nó. Bọc lời gọi bên ngoài trong DB::transaction() để lỡ fail giữa chừng không để lại phân nửa số task bị ẩn.

Restore mà không phá unique

Restore thật ra là insert đội lốt: dòng đó quay lại tập "active" và phải thỏa đúng mấy luật như một dòng mới. Với index ở trên, restore một user mà email đã bị người khác xài lại sẽ fail vì vi phạm constraint. Check trước rồi trả về thông báo cho đàng hoàng:

namespace App\Actions;

use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;

class RestoreUser
{
    public function __invoke(User $user): void
    {
        DB::transaction(function () use ($user): void {
            $taken = User::query()
                ->where('email', $user->email)
                ->whereKeyNot($user->getKey())
                ->lockForUpdate()
                ->exists();

            if ($taken) {
                throw ValidationException::withMessages([
                    'email' => 'Another active account already uses this email address.',
                ]);
            }

            $user->restore();
        });
    }
}

User::query() đã tự loại dòng trashed, nên câu check chỉ nhìn vô tài khoản active, khớp y chang với index.

Dọn dẹp với Prunable

Laravel có sẵn trait Prunable để xóa record cũ theo lịch. Với model soft delete, prune xài forceDelete(), nên dữ liệu trashed cuối cùng cũng rời khỏi database.

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;

class Customer extends Model
{
    use Prunable;
    use SoftDeletes;

    public function prunable(): Builder
    {
        return static::onlyTrashed()->where('deleted_at', '<=', now()->subDays(30));
    }

    protected function pruning(): void
    {
        Storage::disk('s3')->delete("avatars/{$this->id}.jpg");
    }
}

Ghi rõ onlyTrashed(); nó nói lên ý định và làm cho chuyện lỡ tay prune dòng active trở thành không thể. Lên lịch trong routes/console.php bằng Schedule::command('model:prune')->daily(); và chạy thử php artisan model:prune --pretend một lần để coi có bao nhiêu dòng sẽ bị xóa. MassPrunable xóa bằng một query mỗi chunk thay vì load từng model, nhanh hơn nhiều nhưng bỏ qua pruning() và model event.

Kiểm thử hành vi soft delete

Laravel có sẵn assertion cho chuyện này: assertSoftDeleted, assertNotSoftDeleted và assertModelMissing. Test đúng mấy đường đã gãy trong câu chuyện: đăng ký lại, cascade và prune.

use App\Models\Customer;
use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('lets a deleted user sign up again with the same email', function () {
    $old = User::factory()->create(['email' => '[email protected]']);
    $old->delete();

    $this->post('/register', [
        'name' => 'Lan',
        'email' => '[email protected]',
        'password' => 'correct-horse-battery',
        'password_confirmation' => 'correct-horse-battery',
    ])->assertRedirect();

    $this->assertSoftDeleted($old);
    expect(User::where('email', '[email protected]')->count())->toBe(1);
});

it('cascades soft deletes and restores only what it deleted', function () {
    $project = Project::factory()->has(Task::factory()->count(3))->create();
    $deletedEarlier = Task::factory()->for($project)->create();
    $deletedEarlier->delete();

    $this->travel(1)->minutes();
    $project->delete();
    expect($project->tasks()->count())->toBe(0);

    $project->restore();
    expect($project->tasks()->count())->toBe(3);
    $this->assertSoftDeleted($deletedEarlier);
});

it('prunes customers trashed more than 30 days ago', function () {
    $old = Customer::factory()->create();
    $old->delete();
    $this->travel(31)->days();

    $recent = Customer::factory()->create();
    $recent->delete();

    $this->artisan('model:prune', ['--model' => [Customer::class]])->assertSuccessful();

    $this->assertModelMissing($old);
    $this->assertSoftDeleted($recent);
});

Những lỗi hay gặp

  • Unique index thường trên bảng có soft delete. Xài partial index (PostgreSQL) hoặc generated column (MySQL). Đừng bao giờ xài (email, deleted_at).
  • Validation và index nói hai kiểu. Hoặc là withoutTrashed() trên rule cộng với index chỉ unique trên dòng active, hoặc là không cái nào.
  • DB::table() và raw SQL trong báo cáo. Tụi nó bỏ qua scope; dashboard đếm luôn khách hàng đã xóa. Thêm whereNull('deleted_at') cho rõ ràng.
  • Trông chờ foreign key cascade. Nó chỉ chạy khi xóa thật. Cascade trong model event và viết test cho nó.
  • Restore mù quáng. Restore có thể vi phạm unique hoặc đem lại mấy dòng con mà user đã cố ý xóa.
  • Không index deleted_at. Query nào cũng filter trên nó. Với bảng lớn, đưa nó vô composite index.
  • Giữ dữ liệu trashed mãi mãi. Nhớ prune, và nhớ rằng dữ liệu cá nhân bị soft delete thì vẫn là dữ liệu cá nhân.

Khi nào nên xài soft delete, khi nào không

Nên xài khi:

  • User cần undo hay thùng rác, hoặc support cần khôi phục mấy lần lỡ tay.
  • Record khác vẫn phải tham chiếu tới dòng đã xóa (đơn hàng tham chiếu khách hàng).
  • Việc xóa là một sự kiện nghiệp vụ đáng audit, và mình sẽ prune sau thời gian lưu giữ.

Tránh xài khi:

  • Dữ liệu phải biến mất thật (quyền được xóa dữ liệu, secret, token). Hard delete, hoặc ẩn danh hóa.
  • Bảng có lưu lượng lớn và chủ yếu ghi thêm, như log hay event. Xài partition hoặc archive.
  • Mình chỉ cần lịch sử. Một audit log, hoặc trạng thái archived_at mà app coi như trạng thái bình thường, thường rõ ràng hơn một global scope vô hình.

Soft delete là một lời hứa: "đã xóa" nghĩa là "ẩn đi, khôi phục được trong một thời gian, rồi biến mất". Làm sao cho database, validation, relationship và scheduler đều giữ đúng cùng một lời hứa đó.

Thử thách tương tác

Thử thách

Luyện tập ngay điều vừa học. Viết lời giải, mở gợi ý nếu bí.

Đề bài

Mô phỏng hành vi soft delete trong bộ nhớ, kèm luật email unique chỉ áp dụng cho dòng active. Class SoftDeleteStore (PHP và Python) gồm: - create(string $email): int lưu một dòng mới và trả về id, bắt đầu từ 1 và tăng dần. Throw UniqueViolation nếu một dòng ACTIVE đã có email đó; dòng trashed không bao giờ gây trùng. - delete(int $id, int $now): void soft delete một dòng bằng cách set deleted_at = $now. Xóa một dòng đã trashed thì giữ nguyên timestamp ban đầu. - restore(int $id): void xóa deleted_at. Restore dòng đang active thì không làm gì. Throw UniqueViolation nếu một dòng active khác đang xài cùng email. - active(): array trả về id các dòng chưa trashed, tăng dần. - withTrashed(): array (Python: with_trashed()) trả về id của mọi dòng còn lưu, tăng dần. - prune(int $now, int $retentionSeconds): int xóa hẳn các dòng trashed có deleted_at <= $now - $retentionSeconds và trả về số dòng đã xóa. Id không tồn tại trong delete hoặc restore thì throw OutOfBoundsException bên PHP và raise KeyError bên Python.

Code khởi tạo

php
final class UniqueViolation extends RuntimeException {}

final class SoftDeleteStore
{
    /** @var array<int, array{email: string, deleted_at: ?int}> */
    private array $rows = [];

    private int $nextId = 1;

    public function create(string $email): int
    {
        // TODO: throw UniqueViolation if an ACTIVE row already has this email
        //       (trashed rows never conflict); otherwise store it and return the new id (1, 2, 3...)
        return 0;
    }

    public function delete(int $id, int $now): void
    {
        // TODO: OutOfBoundsException for an unknown id
        // TODO: soft delete: set deleted_at = $now, but keep the first timestamp if already trashed
    }

    public function restore(int $id): void
    {
        // TODO: OutOfBoundsException for an unknown id; no-op if the row is active
        // TODO: throw UniqueViolation if ANOTHER active row now uses the same email
        // TODO: otherwise clear deleted_at
    }

    /** @return list<int> */
    public function active(): array
    {
        // TODO: ids of rows that are not trashed, ascending
        return [];
    }

    /** @return list<int> */
    public function withTrashed(): array
    {
        // TODO: ids of all rows that still exist, ascending
        return [];
    }

    public function prune(int $now, int $retentionSeconds): int
    {
        // TODO: permanently remove trashed rows whose deleted_at <= $now - $retentionSeconds
        // TODO: return how many rows were removed
        return 0;
    }
}
python
class UniqueViolation(Exception):
    pass


class SoftDeleteStore:
    def __init__(self) -> None:
        self._rows: dict[int, dict] = {}
        self._next_id = 1

    def create(self, email: str) -> int:
        # TODO: raise UniqueViolation if an ACTIVE row already has this email
        #       (trashed rows never conflict); otherwise store it and return the new id (1, 2, 3...)
        raise NotImplementedError

    def delete(self, row_id: int, now: int) -> None:
        # TODO: KeyError for an unknown id
        # TODO: soft delete: set deleted_at = now, but keep the first timestamp if already trashed
        raise NotImplementedError

    def restore(self, row_id: int) -> None:
        # TODO: KeyError for an unknown id; no-op if the row is active
        # TODO: raise UniqueViolation if ANOTHER active row now uses the same email
        # TODO: otherwise clear deleted_at
        raise NotImplementedError

    def active(self) -> list[int]:
        # TODO: ids of rows that are not trashed, ascending
        raise NotImplementedError

    def with_trashed(self) -> list[int]:
        # TODO: ids of all rows that still exist, ascending
        raise NotImplementedError

    def prune(self, now: int, retention_seconds: int) -> int:
        # TODO: permanently remove trashed rows whose deleted_at <= now - retention_seconds
        # TODO: return how many rows were removed
        raise NotImplementedError

Lời giải của bạn

Gợi ý

Đã mở hết gợi ý
Gợi ý 1

Viết một helper private kiểm tra email có đang được dòng active nào xài không, kèm một id tùy chọn để bỏ qua; create và restore cùng gọi nó.

Gợi ý 2

Lưu deleted_at là null/None cho dòng active để việc check 'active' chỉ là một phép so sánh.

Gợi ý 3

Khi prune, tính cutoff một lần và nhớ là biên có tính luôn dấu bằng (<=).

Gợi ý 4

Bên Python, gom id cần xóa trước rồi mới xóa, để không sửa dict trong lúc đang duyệt.

Lời giải · php
final class UniqueViolation extends RuntimeException {}

final class SoftDeleteStore
{
    /** @var array<int, array{email: string, deleted_at: ?int}> */
    private array $rows = [];

    private int $nextId = 1;

    public function create(string $email): int
    {
        $this->assertEmailFree($email, null);

        $id = $this->nextId++;
        $this->rows[$id] = ['email' => $email, 'deleted_at' => null];

        return $id;
    }

    public function delete(int $id, int $now): void
    {
        $row = $this->find($id);

        if ($row['deleted_at'] === null) {
            $this->rows[$id]['deleted_at'] = $now;
        }
    }

    public function restore(int $id): void
    {
        $row = $this->find($id);

        if ($row['deleted_at'] === null) {
            return;
        }

        $this->assertEmailFree($row['email'], $id);
        $this->rows[$id]['deleted_at'] = null;
    }

    /** @return list<int> */
    public function active(): array
    {
        return array_keys(array_filter($this->rows, fn (array $row): bool => $row['deleted_at'] === null));
    }

    /** @return list<int> */
    public function withTrashed(): array
    {
        return array_keys($this->rows);
    }

    public function prune(int $now, int $retentionSeconds): int
    {
        $cutoff = $now - $retentionSeconds;
        $pruned = 0;

        foreach ($this->rows as $id => $row) {
            if ($row['deleted_at'] !== null && $row['deleted_at'] <= $cutoff) {
                unset($this->rows[$id]);
                $pruned++;
            }
        }

        return $pruned;
    }

    /** @return array{email: string, deleted_at: ?int} */
    private function find(int $id): array
    {
        if (! isset($this->rows[$id])) {
            throw new OutOfBoundsException("Row {$id} does not exist.");
        }

        return $this->rows[$id];
    }

    private function assertEmailFree(string $email, ?int $exceptId): void
    {
        foreach ($this->rows as $id => $row) {
            if ($id !== $exceptId && $row['deleted_at'] === null && $row['email'] === $email) {
                throw new UniqueViolation("Email {$email} is already used by an active row.");
            }
        }
    }
}
Lời giải · python
class UniqueViolation(Exception):
    pass


class SoftDeleteStore:
    def __init__(self) -> None:
        self._rows: dict[int, dict] = {}
        self._next_id = 1

    def create(self, email: str) -> int:
        self._assert_email_free(email, except_id=None)
        row_id = self._next_id
        self._next_id += 1
        self._rows[row_id] = {"email": email, "deleted_at": None}
        return row_id

    def delete(self, row_id: int, now: int) -> None:
        row = self._find(row_id)
        if row["deleted_at"] is None:
            row["deleted_at"] = now

    def restore(self, row_id: int) -> None:
        row = self._find(row_id)
        if row["deleted_at"] is None:
            return
        self._assert_email_free(row["email"], except_id=row_id)
        row["deleted_at"] = None

    def active(self) -> list[int]:
        return sorted(i for i, r in self._rows.items() if r["deleted_at"] is None)

    def with_trashed(self) -> list[int]:
        return sorted(self._rows)

    def prune(self, now: int, retention_seconds: int) -> int:
        cutoff = now - retention_seconds
        doomed = [
            i for i, r in self._rows.items()
            if r["deleted_at"] is not None and r["deleted_at"] <= cutoff
        ]
        for i in doomed:
            del self._rows[i]
        return len(doomed)

    def _find(self, row_id: int) -> dict:
        if row_id not in self._rows:
            raise KeyError(row_id)
        return self._rows[row_id]

    def _assert_email_free(self, email: str, except_id: int | None) -> None:
        for i, r in self._rows.items():
            if i != except_id and r["deleted_at"] is None and r["email"] == email:
                raise UniqueViolation(f"{email} is already used by an active row")

Cùng chủ đề Laravel