Skip to content
PHP Ecosystem
Explore

DeleteBehavior

API reference › Soft Delete › DeleteBehavior

classyii2\extensions\softdelete\DeleteBehavior
Extendsyii\base\Behavior » yii\base\BaseObject
Implementsyii\base\Configurable
Sourcesrc/DeleteBehavior.php

Marks ActiveRecord models as deleted instead of removing their rows, and restores them from that state.

softDelete() writes $softDeleteAttributeValues, restore() writes the restore values, and safeDelete() attempts a physical delete first and marks the record only when the database rejects it with $deleteFallbackException. Yii’s own BaseActiveRecord::delete() keeps deleting the row physically. ScopedQuery and QueryBehavior provide query scoping.

The owner may declare public beforeSoftDelete(), afterSoftDelete(), beforeRestore() and afterRestore() methods; the behavior calls them by name before triggering the matching event. A before-method returning a falsy value cancels the operation.

Every write targets the row by its persisted primary key and honors BaseActiveRecord::optimisticLock(), whose value must be a non-negative integer that still matches the row and that each update increments. A record without its primary key loaded, a hook that is not public, or a transactional operation on an owner without a Yii SQL connection raises InvalidConfigException.

Exceptions from hooks, event handlers and the database propagate. A rolled-back transaction first returns the owner attributes to their state before the call; when the rollback itself fails, RuntimeException reports it with the exception that caused the rollback as its previous one.

PropertyTypeDescriptionDefined by
$allowDeleteCallbackmixedCallback that decides whether softDelete() deletes the row physically instead of marking it, or null to always mark it. Default: null.DeleteBehavior
$deleteFallbackExceptionstringClass name of the Throwable that makes safeDelete() fall back to a soft delete when the physical delete raises it or one of its subclasses. Default: \yii\db\IntegrityException::class.DeleteBehavior
$invokeDeleteEventsboolWhether softDelete() runs the owner’s BaseActiveRecord::beforeDelete() and BaseActiveRecord::afterDelete(). Default: true.DeleteBehavior
$owneryii\base\T|nullThe owner of this behavior Default: null.yii\base\Behavior
$restoreAttributeValuesarray<string, mixed>|nullValues written on restoration, by attribute name. Default: null.DeleteBehavior
$softDeleteAttributeValuesarray<string, mixed>Values written on soft deletion, by attribute name, such as a flag or a status: php ['isDeleted' => true] ['statusId' => Item::STATUS_DELETED] A non-scalar callable is a computed value: it receives the owner and returns the value to write. Default: ['isDeleted' => true].DeleteBehavior
$useRestoreAttributeValuesAsDefaultsboolWhether inserting a record fills its null attributes with the restore values. Default: false.DeleteBehavior
MethodDescriptionDefined by
__construct()Constructor.yii\base\BaseObject
__call()Calls the named method which is not a class method.yii\base\BaseObject
__get()Returns the value of an object property.yii\base\BaseObject
__isset()Checks if a property is set, i.e. defined and not null.yii\base\BaseObject
__set()Sets value of an object property.yii\base\BaseObject
__unset()Sets an object property to null.yii\base\BaseObject
afterRestore()Runs the owner’s public afterRestore(), when declared, and triggers EVENT_AFTER_RESTORE.DeleteBehavior
afterSoftDelete()Runs the owner’s public afterSoftDelete(), when declared, and triggers EVENT_AFTER_SOFT_DELETE.DeleteBehavior
attach()Attaches the behavior object to the component.yii\base\Behavior
beforeInsert()Fills the null attributes of a record being inserted with the restore values while $useRestoreAttributeValuesAsDefaults is enabled; handles BaseActiveRecord::EVENT_BEFORE_INSERT.DeleteBehavior
beforeRestore()Runs the owner’s public beforeRestore(), when declared, and triggers EVENT_BEFORE_RESTORE.DeleteBehavior
beforeSoftDelete()Runs the owner’s public beforeSoftDelete(), when declared, and triggers EVENT_BEFORE_SOFT_DELETE.DeleteBehavior
canGetProperty()Returns a value indicating whether a property can be read.yii\base\BaseObject
canSetProperty()Returns a value indicating whether a property can be set.yii\base\BaseObject
className() staticReturns the fully qualified name of this class.yii\base\BaseObject
detach()Detaches the behavior object from the component.yii\base\Behavior
events()Registers the owner event that can apply active marker defaults before insertion.DeleteBehavior
hasMethod()Returns a value indicating whether a method is defined.yii\base\BaseObject
hasProperty()Returns a value indicating whether a property is defined.yii\base\BaseObject
init()Initializes the object.yii\base\BaseObject
resolveRestoreAttributeValues()Returns the values written on restoration.DeleteBehavior
restore()Restores a soft-deleted record by writing the restore values together with its other changed attributes.DeleteBehavior
safeDelete()Deletes the row physically and marks the record as deleted instead when the database rejects the delete with $deleteFallbackException.DeleteBehavior
softDelete()Marks the record as deleted by writing $softDeleteAttributeValues together with its other changed attributes, or deletes it physically when $allowDeleteCallback allows it.DeleteBehavior
isDeleteAllowed() protectedReturns whether softDelete() deletes the row physically, as decided by $allowDeleteCallback.DeleteBehavior
restoreInternal() protectedWrites the restore values together with the other changed owner attributes.DeleteBehavior
softDeleteInternal() protectedRuns the soft-delete hooks around writing $softDeleteAttributeValues with the other changed attributes.DeleteBehavior
EventTypeDescriptionDefined by
EVENT_AFTER_RESTOREyii\base\EventTriggered after a record is restored. Event name: 'afterRestore'.DeleteBehavior
EVENT_AFTER_SOFT_DELETEyii\base\EventTriggered after a record is marked as deleted. Event name: 'afterSoftDelete'.DeleteBehavior
EVENT_BEFORE_RESTOREyii\base\ModelEventTriggered before a record is restored; set ModelEvent::$isValid to false to cancel. Event name: 'beforeRestore'.DeleteBehavior
EVENT_BEFORE_SOFT_DELETEyii\base\ModelEventTriggered before a record is marked as deleted; set ModelEvent::$isValid to false to cancel. Event name: 'beforeSoftDelete'.DeleteBehavior
public mixed $allowDeleteCallback = null

Callback that decides whether softDelete() deletes the row physically instead of marking it, or null to always mark it.

The callback receives the owner and must return a bool; any other callback result, or a value that is not callable, makes softDelete() throw InvalidConfigException.

static fn (\yii\db\BaseActiveRecord $user): bool => $user->lastLoginDate === null
public string $deleteFallbackException = \yii\db\IntegrityException::class

Class name of the Throwable that makes safeDelete() fall back to a soft delete when the physical delete raises it or one of its subclasses.

The default handles database integrity failures such as a restrictive foreign key. A value that does not name a Throwable type makes safeDelete() throw InvalidConfigException.

public bool $invokeDeleteEvents = true

Whether softDelete() runs the owner’s BaseActiveRecord::beforeDelete() and BaseActiveRecord::afterDelete().

The soft-delete hooks and events run in either case.

public array<string, mixed>|null $restoreAttributeValues = null

Values written on restoration, by attribute name.

When null, resolveRestoreAttributeValues() infers them from $softDeleteAttributeValues.

public array<string, mixed> $softDeleteAttributeValues = ['isDeleted' => true]

Values written on soft deletion, by attribute name, such as a flag or a status: php ['isDeleted' => true] ['statusId' => Item::STATUS_DELETED] A non-scalar callable is a computed value: it receives the owner and returns the value to write.

A string is always a literal value, even when it names a function.

['deletedAt' => static fn (\yii\db\BaseActiveRecord $model): int => time()]
public function afterRestore(): void

Runs the owner’s public afterRestore(), when declared, and triggers EVENT_AFTER_RESTORE.

Throws

public function afterSoftDelete(): void

Runs the owner’s public afterSoftDelete(), when declared, and triggers EVENT_AFTER_SOFT_DELETE.

Throws

public function beforeInsert(yii\base\Event $event): void

Fills the null attributes of a record being inserted with the restore values while $useRestoreAttributeValuesAsDefaults is enabled; handles BaseActiveRecord::EVENT_BEFORE_INSERT.

Parameters

ParameterTypeDescription
$eventyii\base\Event

Throws

public function beforeRestore(): bool

Runs the owner’s public beforeRestore(), when declared, and triggers EVENT_BEFORE_RESTORE.

Returns

bool: Whether the restoration may proceed; false when the owner method returns a falsy value, in which case the event is not triggered, or when an event handler invalidates the event.

Throws

public function beforeSoftDelete(): bool

Runs the owner’s public beforeSoftDelete(), when declared, and triggers EVENT_BEFORE_SOFT_DELETE.

Returns

bool: Whether the soft deletion may proceed; false when the owner method returns a falsy value, in which case the event is not triggered, or when an event handler invalidates the event.

Throws

public function events(): array<string, string>

Registers the owner event that can apply active marker defaults before insertion.

Returns

array<string, string>: Owner events handled by the behavior.

public function resolveRestoreAttributeValues(): array<string, mixed>

Returns the values written on restoration.

Returns $restoreAttributeValues when set. Otherwise infers each value from $softDeleteAttributeValues: a bool is negated, 0 and 1 swap, and a computed value restores to null.

Returns

array<string, mixed>: Values by attribute name.

Throws

public function restore(): false|int

Restores a soft-deleted record by writing the restore values together with its other changed attributes.

Runs inside a transaction when the owner declares ActiveRecord::OP_UPDATE transactional.

Returns

false|int: Number of restored rows; 0 for an unsaved record, when no value differs from the loaded ones, or when no row matched; false when a hook or event handler cancels the restoration.

Throws

public function safeDelete(): false|int

Deletes the row physically and marks the record as deleted instead when the database rejects the delete with $deleteFallbackException.

Requires a SQL ActiveRecord owner. The physical attempt runs BaseActiveRecord::beforeDelete() and BaseActiveRecord::afterDelete() inside a transaction. When the physical delete raises an eligible exception, that transaction is rolled back and the soft deletion runs in a new one. An exception raised by a hook is never eligible.

Returns

false|int: Number of deleted or marked rows; 0 for an unsaved record or when no row matched; false when a hook or event handler cancels the operation.

Throws

public function softDelete(): false|int

Marks the record as deleted by writing $softDeleteAttributeValues together with its other changed attributes, or deletes it physically when $allowDeleteCallback allows it.

Marking the record runs inside a transaction when the owner declares ActiveRecord::OP_DELETE or ActiveRecord::OP_UPDATE transactional. The physical delete is BaseActiveRecord::delete(), which follows ActiveRecord::OP_DELETE alone.

Returns

false|int: Number of affected rows; 0 for an unsaved record, when no value differs from the loaded ones, or when no row matched; false when a hook or event handler cancels the operation.

Throws

protected function isDeleteAllowed(): bool

Returns whether softDelete() deletes the row physically, as decided by $allowDeleteCallback.

Returns

bool: Whether the physical delete is allowed; false when no callback is configured.

Throws

protected function restoreInternal(): int

Writes the restore values together with the other changed owner attributes.

Returns

int: Number of restored rows.

Throws

protected function softDeleteInternal(): false|int

Runs the soft-delete hooks around writing $softDeleteAttributeValues with the other changed attributes.

Returns

false|int: Number of rows marked as deleted, or false when a hook or event handler cancels.

Throws