PHP code example of illuminatech / db-safedelete

1. Go to this page and download the library: Download illuminatech/db-safedelete 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/ */

    

illuminatech / db-safedelete example snippets




namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminatech\DbSafeDelete\SafeDeletes;

class Customer extends Model
{
    use SafeDeletes;

    public function purchases()
    {
        return $this->hasMany(Purchase::class);
    }

    // ...
}

// if there is a foreign key reference :
$customerWithReference = Customer::query()
    ->whereHas('purchases')
    ->first();

$customerWithReference->delete(); // performs "soft" delete!

// if there is NO foreign key reference :
$customerWithoutReference = Customer::query()
    ->whereDoesntHave('purchases')
    ->first();

$customerWithoutReference->delete(); // performs actual delete!



namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminatech\DbSafeDelete\SafeDeletes;

class User extends Model
{
    use SafeDeletes;

    public function forceDeleteAllowed(): bool
    {
        return $this->last_login_at === null;
    }

    // ...
}

$user = User::query()->whereNull('last_login_at')->first();
$user->delete(); // removes the record!!!

$user = User::query()->whereNotNull('last_login_at')->first();
$user->delete(); // marks record as "trashed"



// if there is a foreign key reference :
$customerWithReference = Customer::query()
    ->whereHas('purchases')
    ->first();

$customerWithReference->forceDelete(); // performs actual delete (triggers a database error actually)!

// if there is NO foreign key reference :
$customerWithoutReference = Customer::query()
    ->whereDoesntHave('purchases')
    ->first();

$customerWithoutReference->softDelete(); // performs "soft" delete!

// if there is a foreign key reference :
$customerWithReference = Customer::query()
    ->whereHas('purchases')
    ->first();

$customerWithReference->safeDelete(); // performs "soft" delete!

// if there is NO foreign key reference :
$customerWithoutReference = Customer::query()
    ->whereDoesntHave('purchases')
    ->first();

$customerWithoutReference->safeDelete(); // performs actual delete!