Search by

yii2-extensions / soft-delete

terabytesoftw

Soft deletion and restoration for Yii2 ActiveRecord

Package info

github.com/yii2-extensions/soft-delete

Homepage

Documentation

Type:yii2-extension

pkg:composer/yii2-extensions/soft-delete

Statistics

Installs: 1

Dependents: 0

Suggesters: 0

Stars: 1

Open Issues: 0

0.1.0 2026-11-27 11:48 UTC

This package is auto-updated.

Last update: 2026-11-27 14:40:00 UTC


README

Yii Framework

Soft Delete


PHPUnit Coverage Mutation Testing PHPStan

Soft deletion and restoration for Yii2 ActiveRecord
Mark records as deleted without losing them, and restore them when needed

Features

Feature Overview

Quick start

Installation

Install the package with Composer:

composer require yii2-extensions/soft-delete:^0.1

Applications on Yii 2.0 need a Bower asset source such as Asset Packagist. The Installation Guide covers it, together with Yii 22 and local checkouts.

Usage

A billing schema: customer has a country and a nullable deleted_at timestamp. invoice references it through a customer_id foreign key and has a status and an is_void boolean that defaults to false.

use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii2\extensions\softdelete\DeleteBehavior;
use yii2\extensions\softdelete\ScopedQuery;

final class Customer extends ActiveRecord
{
    public function behaviors(): array
    {
        return [
            'softDelete' => [
                'class' => DeleteBehavior::class,
                // Stamp the deletion time. restore() writes null back, and the scopes test IS [NOT] NULL.
                'softDeleteAttributeValues' => ['deleted_at' => static fn(): int => time()],
            ],
        ];
    }

    // Hide deleted customers by default: findOne(), relations, joins and eager loading all start here.
    public static function find(): ScopedQuery
    {
        return (new ScopedQuery(self::class))->notDeleted();
    }

    public function getInvoices(): ActiveQuery
    {
        return $this->hasMany(Invoice::class, ['customer_id' => 'id']);
    }
}

final class Invoice extends ActiveRecord
{
    public function behaviors(): array
    {
        return [
            'softDelete' => [
                'class' => DeleteBehavior::class,
                'softDeleteAttributeValues' => ['is_void' => true],
                // A draft never reached the ledger, so softDelete() removes its row instead of marking it.
                'allowDeleteCallback' => static fn(Invoice $invoice): bool => $invoice->status === 'draft',
            ],
        ];
    }

    public static function find(): ScopedQuery
    {
        return (new ScopedQuery(self::class))->notDeleted();
    }

    // A paid invoice cannot be voided: softDelete() returns false and writes nothing.
    public function beforeSoftDelete(): bool
    {
        return $this->status !== 'paid';
    }
}

The scopes follow each query through aliases, joins and filters:

// Active customers with an overdue invoice. Each table keeps its scope under its own alias,
// and voided invoices are excluded inside the JOIN, not after it.
$debtors = Customer::find()
    ->alias('c')
    ->innerJoinWith('invoices i')
    ->andWhere(['i.status' => 'overdue'])
    ->all();

// Removes the row when nothing references it. While an invoice still does, the foreign key
// rejects the delete and the customer is marked as deleted instead.
$customer->safeDelete();

// One call per invoice, three outcomes: a draft is removed, a paid one is refused, any other is voided.
$invoice->softDelete();

// Switch scope without losing the other filters.
$deleted = Customer::find()
    ->deleted()
    ->andWhere(['country' => 'CL'])
    ->all();
$total = Customer::find()
    ->withDeleted()
    ->count();

// Bring a customer back.
Customer::find()
    ->deleted()
    ->andWhere(['id' => $id])
    ->one()
    ?->restore();

filterDeleted() maps a request value to a scope, and writes honor optimistic locking; the Usage Examples show both. The Configuration Guide details transactions and the foreign-key fallback.

Documentation

Practical guides for configuring soft deletion, querying records, and running the test suite.

The guides and the API reference generated from the PHPDoc in src/ are available at https://yii2-framework.github.io/docs/extensions/soft-delete/.

AI assistance

AI agents: read the documentation index and fetch the Markdown version of a page by appending index.md to its URL. The AI agents guide covers skill installation, client setup and verification.

The hosted documentation covers Yii 22.0. If it does not match the installed revision or is unavailable, use the repository guides, the skill source, the source PHPDoc and the changelog.

Package information

PHP Yii 2.0.55+ Yii 22.0.x

Project status

PHPStan Level Max Quality StyleCI

Security

OpenSSF Scorecard Zizmor

Built with AI

Built with Claude Code Built with Codex Reviewed by CodeRabbit

Our social networks

Follow on X Follow on Facebook Join our Subreddit Join on Telegram

License

Based on Yii2tech AR Soft Delete, originally developed by Paul Klimov.

License