PHP code example of funayaki / cakephp3-soft-delete

1. Go to this page and download the library: Download funayaki/cakephp3-soft-delete library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

funayaki / cakephp3-soft-delete example snippets


// In /config/bootstrap.php
Plugin::load('SoftDelete');

// in src/Model/Table/UsersTable.php
...
use SoftDelete\Model\Table\Entity\SoftDeleteAwareInterface;
use SoftDelete\Model\Table\SoftDeleteTrait;

class UsersTable extends Table implements SoftDeleteAwareInterface
{
    use SoftDeleteTrait;

    public function getSoftDeleteField()
    {
        return 'deleted';
    }

    public function getSoftDeleteValue()
    {
        return date('Y-m-d H:i:s');
    }

    public function getRestoreValue()
    {
        return null;
    }
}

// in src/Model/Table/UsersTable.php
$this->delete($user); // $user entity is now soft deleted if UsersTable uses SoftDeleteTrait.

// in src/Model/Table/UsersTable.php
// Let's suppose $user #1 is soft deleted.
$user = $this->Users->find('all', ['withDeleted'])->where('id', 1)->first();
$this->restore($user); // $user #1 is now restored.

// in src/Model/Table/UsersTable.php
$nonSoftDeletedRecords = $this->find('all');
$allRecords            = $this->find('all', ['withDeleted']);

// in src/Model/Table/UsersTable.php
$user = $this->get($userId);
$success = $this->hardDelete($user);

// in src/Model/Table/UsersTable.php
$date = new \DateTime('some date');
$affectedRowsCount = $this->hardDeleteAll([
    $this->getSoftDeleteField() . ' <=' => $date->format('Y-m-d H:i:s')
]);