A customer deletes her account in March. In May she comes back and tries to sign up with the same email. The form says "The email has already been taken", even though the admin panel shows no such user. Support "fixes" it by switching the validation to ignore trashed rows, and now signup crashes with SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry because the unique index on users.email still sees the soft-deleted row. The same week, the orders page starts throwing Attempt to read property "name" on null for every order placed by a customer who closed their account.
Soft deletes look like a one-line feature: add use SoftDeletes, add a deleted_at column, done. In practice they change the meaning of "exists" across your whole schema, and the database does not know about that change. Unique constraints, foreign keys, cascades, relationships and raw queries all keep treating soft-deleted rows as perfectly alive. This tip walks through the traps and the patterns that actually hold up in production.
How Soft Deletes Actually Work
The SoftDeletes trait does two things. delete() runs an UPDATE ... SET deleted_at = now() instead of a DELETE, and a global scope adds WHERE deleted_at IS NULL to every Eloquent query for that model. That is all. Everything else follows from those two facts:
withTrashed()removes the scope,onlyTrashed()flips it todeleted_at IS NOT NULL.restore()setsdeleted_atback toNULL;forceDelete()runs a realDELETE.$model->trashed()tells you whether an instance is soft deleted.- The scope lives in Eloquent only.
DB::table('users'), raw SQL, database views, reporting tools and the database's own constraints all see every row.
So the database thinks a soft-deleted user still exists, and your app thinks it does not. Every bug below comes from that mismatch.
The Lifecycle of a Soft-Deleted Row
A row should not sit in the trashed state forever. Decide upfront how long trashed data is kept (for undo, audits or legal reasons), and prune it after that. Otherwise "deleted" accounts keep personal data indefinitely, which is a compliance problem in its own right.
Unique Indexes vs deleted_at
The signup bug has two halves: validation and the index. A plain unique:users,email rule is a raw database query, so it counts trashed rows. And a plain unique index on email blocks a second row with the same email, trashed or not.
The tempting fix is a composite unique index on (email, deleted_at). It does not work: in both MySQL and PostgreSQL, NULL values are distinct from each other in unique indexes, so two active rows with the same email (both deleted_at IS NULL) are allowed. You traded one bug for a worse one.
What you want is "unique among active rows". On PostgreSQL that is a partial index. On MySQL, use a generated column that is NULL for trashed rows, and put the unique index on it; multiple NULLs are allowed, so trashed rows never conflict.
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');
});
}
};
Then align validation with the index: Rule::unique('users', 'email')->withoutTrashed() only counts rows where deleted_at is null. Validation gives the user a friendly message; the index is what actually guarantees correctness under concurrent signups. You need both.
Relationships Pointing at Trashed Rows
Soft deleting a customer does not touch their orders. $order->customer runs an Eloquent query, the global scope hides the trashed customer, and you get null. Any view that does $order->customer->name crashes.
Decide per relationship what the business wants. For historical records such as orders, invoices and audit logs, the related record should still be visible, so include trashed rows in the relationship itself:
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();
}
}
For admin screens that open a trashed record by URL, route model binding returns a 404 by default. Opt in per route with Route::get('/admin/customers/{customer}', ShowCustomer::class)->withTrashed();. And in Blade, show the state explicitly (@if ($order->customer->trashed())) instead of pretending the customer is active.
Cascading Soft Deletes (and Restores)
ON DELETE CASCADE on a foreign key fires on DELETE. A soft delete is an UPDATE, so the database cascades nothing. If deleting a project should also hide its tasks, you must do it in the application, and you must do the reverse on 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());
});
}
}
Three details make this correct rather than just plausible. The cascade runs in deleted (after the project got its timestamp), so task timestamps are never earlier than the project's. The restore only brings back tasks trashed at or after the project, so a task the user deleted on purpose last month stays deleted. And on forceDelete we skip the loop because the real foreign key cascade handles it. Deleting one model at a time fires events for each task, which is what you want if tasks cascade further; for very large children, a single update(['deleted_at' => now()]) query is faster but skips their events. Wrap the outer call in DB::transaction() so a failure halfway does not leave half the tasks hidden.
Restoring Without Breaking Uniqueness
Restoring is an insert in disguise: the row re-enters the "active" set and must satisfy the same rules as a new row. With the index above, restoring a user whose email has since been reused fails with a constraint violation. Check first and return a proper message:
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() already excludes trashed rows, so the check only looks at active accounts, matching the index exactly.
Pruning with Prunable
Laravel ships the Prunable trait for deleting old records on a schedule. For soft-deleting models, pruning uses forceDelete(), so trashed data finally leaves the 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");
}
}
Be explicit with onlyTrashed(); it documents intent and makes it impossible to prune active rows by mistake. Schedule it in routes/console.php with Schedule::command('model:prune')->daily(); and run php artisan model:prune --pretend once to see how many rows would go. MassPrunable deletes with one query per chunk instead of loading models, which is much faster but skips pruning() and model events.
Testing Soft Delete Behaviour
Laravel has assertions made for this: assertSoftDeleted, assertNotSoftDeleted and assertModelMissing. Test the paths that broke in the story: re-signup, cascading and pruning.
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);
});
Common Pitfalls
- Plain unique index on a soft-deleted table. Use a partial index (PostgreSQL) or a generated column (MySQL). Never
(email, deleted_at). - Validation and index disagreeing.
withoutTrashed()on the rule plus "active only" uniqueness in the index, or neither. DB::table()and raw SQL in reports. They ignore the scope; dashboards count deleted customers. AddwhereNull('deleted_at')explicitly.- Expecting foreign key cascades. They only fire on real deletes. Cascade in model events and test it.
- Restoring blindly. A restore can violate uniqueness or bring back children the user deleted on purpose.
- No index on
deleted_at. Every query filters on it. On large tables, include it in your composite indexes. - Keeping trashed data forever. Prune, and remember that soft-deleted personal data is still personal data.
When to Use Soft Deletes and When Not To
Use them when:
- Users need undo or a recycle bin, or support needs to restore mistakes.
- Other records must keep referencing the deleted one (orders referencing a customer).
- Deletion is a business event worth auditing, and you will prune after a retention period.
Avoid them when:
- Data must really be gone (right to erasure, secrets, tokens). Hard delete, or anonymise.
- The table is high-volume and append-heavy, such as logs or events. Partition or archive instead.
- You only want history. An audit log or an
archived_atstatus that the app treats as a normal state is often clearer than an invisible global scope.
Soft deletes are a promise that "deleted" means "hidden, recoverable for a while, then gone". Make the database, the validation, the relationships and the scheduler all keep that same promise.
Try the challenge
Practice what you just learned. Write your solution, reveal hints if you get stuck.
Instructions
Model soft delete semantics in memory, including a unique email that only applies to active rows. Class SoftDeleteStore (PHP and Python) with: - create(string $email): int stores a new row and returns its id, starting at 1 and incrementing. Throw UniqueViolation if an ACTIVE row already has the same email; trashed rows never conflict. - delete(int $id, int $now): void soft deletes a row by setting deleted_at = $now. Deleting an already trashed row keeps the original timestamp. - restore(int $id): void clears deleted_at. Restoring an active row does nothing. Throw UniqueViolation if another active row now uses the same email. - active(): array returns the ids of non-trashed rows, ascending. - withTrashed(): array (Python: with_trashed()) returns the ids of all rows still stored, ascending. - prune(int $now, int $retentionSeconds): int permanently removes trashed rows whose deleted_at <= $now - $retentionSeconds and returns how many were removed. An unknown id in delete or restore throws OutOfBoundsException in PHP and raises KeyError in Python.
Starter code
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;
}
}
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
Your solution
Hints
All hints revealedWrite one private helper that checks whether an email is used by an active row, with an optional id to ignore; create and restore both call it.
Store deleted_at as null/None for active rows so 'active' is a single comparison.
When pruning, compute the cutoff once and remember the boundary is inclusive (<=).
In Python, collect the ids to delete first and remove them afterwards, so you do not mutate the dict while iterating.
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.");
}
}
}
}
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")

