Skip to content
CODE THE PIXEL
On this page
CakePHP

CakePHP 4 Soft Delete

Asyraf Wahi Anuar 5 min read

A soft delete marks a record as no longer active or valid without deleting it from the database. Soft deletion is a widely used pattern applied for business applications.

This tutorial may be outdated

It was last reviewed 3 years ago. Some steps may differ in newer versions.

Tech stack

  • CakePHP 4.x

A soft delete marks a record as no longer active or valid without deleting it from the database. Soft deletion is a widely used pattern applied for business applications. It allows users to mark some records as deleted without erasure from the database. Effectively, the user prevents a soft-deleted record from being selected; meanwhile, all old records can still refer to it. Hard deletes are hard to recover if something goes wrong (application bug, bad migration, manual query, etc.). This usually involves restoring from a backup, and targeting only the data affected by the bad delete is hard. Soft deletes are easier to recover from once the user determines what happened. This tutorial will demonstrate how to apply the soft delete method in CakePHP 4 using 'useMuffin Trash' plugin.

Installation

Download using composer:

Terminal
composer require muffin/trash

Load the plugin:

Terminal
cake plugin load Muffin/Trash

Usage

You database should have DATETIME column 'deleted' or 'trashed'. If use different name, you need to identify the specific column name in behavior.

In the table(s) model, add the Trash behavior as shown below:

PHP
$this->addBehavior('Muffin/Trash.Trash');

The behaviour will default auto-detect the DATETIME column used to track trashed (soft-deleted) records, but only if you use deleted or trashed names. Otherwise, you could customize that when adding the behaviour:

PHP
$this->addBehavior('Muffin/Trash.Trash', [
    'field' => 'deleted_at'
]);

or, at the global level, in bootstrap.php:

PHP
Configure::write('Muffin/Trash.field', 'deleted_at');

Add the following code in controller header:

PHP
use Muffin\Trash\Model\Behavior\TrashBehavior;
use Cake\ORM\Entity;

To restore all trashed records, add the following function:

PHP
public function restoreAllTrash()
{
    $this->Playgrounds->restoreTrash();
    $this->Flash->success(__('All records has been restored'));
    return $this->redirect(['action' => 'index']);
}

To restore a specific trashed entity, use the following function:

PHP
public function restoreTrashEntity($id = null)
{
    $this->Playgrounds->restoreTrash(new Entity([
        'id' => $id,
    ], ['markNew' => false, 'markClean' => true]));
    
    return $this->redirect(['action' => 'find-only-trashed']);
}

To transfer all records to trash, use the following code. It will trash all records in the database:

PHP
public function trashAll()
{
    $this->Playgrounds->trashAll('1 = 1');
    $this->Flash->success(__('All record has been deleted'));
    return $this->redirect(['action' => 'index']);
}

To list all trashed records, use the following code:

PHP
public function findOnlyTrashed()
{
    $this->paginate = [
        'maxLimit' => 10,
    ];
    $playgrounds = $this->paginate($this->Playgrounds->find('onlyTrashed'));
    
    $this->set(compact('playgrounds'));
}

To empty the trashed records, use the following code. This action will hard-delete the records from the database.

PHP
public function emptyTrash()
{
    $this->Playgrounds->emptyTrash();
    $this->Flash->success(__('Trash Empty'));
    return $this->redirect(['action' => 'find-only-trashed']);
}

That's all. Happy coding :)

Did this tutorial help?

65 readers found this helpful

Comments

No comments yet. Questions about this tutorial are welcome here: the answer helps the next reader too.

Leave a comment

Markdown works: `code`, ``` blocks, **bold**, links.

First comments are reviewed before they appear.

CakePHP

CakePHP 4 Audit Trail Using AuditStash Plugin

This plugin adds an "audit trail" to any of your Table classes in your application, allowing the web applications to record the creation, change, or deletion of any table's entities. In theory, it will store the old data before replacing it with the new data or content.

3 min read

CakePHP

CakePHP 4 HTML Minify Plugin

Minify HTML source code for CakePHP 4. Minification enhances site performance and accessibility significantly, which immediately translates into a better user experience.

2 min read

CakePHP

CakePHP 4 Audit Log Plugin

An audit trail (audit logs) is a chronological log meant to capture any changes made to the electronic contents. The logs are used to be evidence for any changes that affected the contents.

3 min read