PHP

Soft-Delete Pattern

admin by @admin ADMIN
Jun 15, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Mark rows as deleted instead of removing them. A small helper class keeps the WHERE deleted_at IS NULL filter out of every query you write.
PHP
Raw
<?php
final class SoftDeleteRepo {
    public function __construct(private PDO $db, private string $table) {}

    public function find(int $id): ?array {
        $s = $this->db->prepare("SELECT * FROM {$this->table} WHERE id=? AND deleted_at IS NULL");
        $s->execute([$id]);
        return $s->fetch() ?: null;
    }

    public function all(): array {
        return $this->db->query("SELECT * FROM {$this->table} WHERE deleted_at IS NULL")->fetchAll();
    }

    public function softDelete(int $id): void {
        $this->db->prepare("UPDATE {$this->table} SET deleted_at = NOW() WHERE id=? AND deleted_at IS NULL")
                 ->execute([$id]);
    }

    public function restore(int $id): void {
        $this->db->prepare("UPDATE {$this->table} SET deleted_at = NULL WHERE id=?")->execute([$id]);
    }
}

$users = new SoftDeleteRepo($db, 'users');
$users->softDelete(42);    // keeps the row, hides it from find/all
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.