PHP code example of krishnaraj / laravel-cascading-soft-deletes

1. Go to this page and download the library: Download krishnaraj/laravel-cascading-soft-deletes 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/ */

    

krishnaraj / laravel-cascading-soft-deletes example snippets


use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Krishnaraj\LaravelCascadingSoftDeletes\Traits\CascadesSoftDeletes;

class User extends Model
{
    use SoftDeletes, CascadesSoftDeletes;

    // List the relationships you want to cascade
    protected $cascadeRelationships = ['posts', 'profile'];

    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }

    public function profile(): HasOne
    {
        return $this->hasOne(Profile::class);
    }
}

$user->delete();    // Soft-deletes user, posts, and profile
$user->restore();   // Restores user, posts, and profile
$user->forceDelete(); // Permanently deletes user, posts, and profile

protected $cascadeRelationships = ['posts', 'profile', 'addresses'];

// User → Posts → Comments
protected $cascadeRelationships = ['posts.comments'];

// Even deeper — 3 levels (the default max)
protected $cascadeRelationships = ['posts.comments.replies'];

protected $cascadeRelationships = ['roles', 'tags'];

public function roles(): BelongsToMany
{
    return $this->belongsToMany(Role::class);
}

$post->delete();   // Post deleted independently, no tracking record

$user->delete();   // User cascade-deletes only other posts (post above is already trashed)
$user->restore();  // User restored — independently-deleted post stays deleted ✅

$team->delete();  // Team cascade-deletes Post, tracking record created
$user->delete();  // User tries to cascade-delete Post — already trashed, no tracking entry

$user->restore(); // Post stays deleted (Team still holds it)
$team->restore(); // Post now restored ✅

return [

    // The database table used to track cascade deletions
    'table_name' => 'cascade_deletions',

    // Maximum allowed nesting depth for relationship paths (default: 3)
    // e.g. 'posts.comments.replies' = depth 3
    'max_nesting_level' => 3,

    // Wrap cascade operations in a DB transaction (default: true)
    'use_transaction' => true,

    // Re-throw exceptions encountered during cascade (default: true)
    // Set to false to silently log errors instead
    'throw_on_error' => true,

    // Roll back the transaction if an error occurs (default: true)
    'rollback_on_error' => true,

    // Cascade restores to children when a parent is restored (default: true)
    'cascade_on_restore' => true,

    // Detach BelongsToMany pivot records on delete (default: true)
    'detach_belongs_to_many' => true,

];

class User extends Model
{
    use SoftDeletes, CascadesSoftDeletes;

    protected $cascadeRelationships = ['posts', 'profile'];

    // Override defaults per model:
    protected $cascadeNestingLimit       = 5;     // Allow deeper nesting for this model
    protected $cascadeUseTransaction     = true;  // Use transactions
    protected $cascadeThrowOnError       = false; // Suppress errors silently
    protected $cascadeRollbackOnError    = true;  // Roll back on error
    protected $cascadeOnRestore          = true;  // Cascade restores
    protected $cascadeDetachBelongsToMany = false; // Keep pivot records on delete
}

public function cascadeRelationships(): array
{
    return ['posts', 'profile'];
}

// Global
'max_nesting_level' => 5,

// Per model
protected $cascadeNestingLimit = 5;

$user->forceDelete(); // Permanently removes user + all cascade children

use Krishnaraj\LaravelCascadingSoftDeletes\Models\CascadeDeletion;

// Find all cascade records where a User is the parent
CascadeDeletion::forParent($user)->get();

// Find all cascade records where a Post is the child
CascadeDeletion::forChild($post)->get();

try {
    $user->delete();
} catch (\Throwable $e) {
    // handle
}

protected $cascadeThrowOnError = false;

// If 'nonExistentRelation' throws, the whole cascade is rolled back
protected $cascadeRelationships = ['posts', 'nonExistentRelation'];
protected $cascadeRollbackOnError = true;
bash
php artisan migrate
bash
php artisan vendor:publish --tag=cascading-soft-deletes-config
bash
php artisan vendor:publish --tag=cascading-soft-deletes-migrations

src/
├── CascadingSoftDeletesServiceProvider.php   # Auto-discovery service provider
├── Traits/
│   └── CascadesSoftDeletes.php              # Attach to your Eloquent models
├── Services/
│   └── CascadeService.php                   # Core cascade logic
├── Models/
│   └── CascadeDeletion.php                  # Eloquent model for tracking table
└── Exceptions/
    ├── InvalidRelationshipException.php
    └── NestingLimitExceededException.php
config/
└── cascading-soft-deletes.php               # Package configuration
database/migrations/
└── create_cascade_deletions_table.php       # Tracking table migration