Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Cascade Delete Laravel Package

cesargb/laravel-cascade-delete

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cesargb/laravel-cascade-delete
    

    No additional configuration is required beyond publishing the package (though none is needed by default).

  2. First Use Case: Apply the CascadeDelete trait to a model with polymorphic relationships:

    use Cesargb\Database\Support\CascadeDelete;
    
    class ParentModel extends Model
    {
        use CascadeDelete;
    
        // Define polymorphic relationships
        public function morphOneRelation()
        {
            return $this->morphOne(RelatedModel::class, 'parentable');
        }
    
        public function morphManyRelation()
        {
            return $this->morphMany(RelatedModel::class, 'parentable');
        }
    
        // Declare which polymorphic methods to cascade
        protected $cascadeDeleteMorph = [
            'morphOneRelation',
            'morphManyRelation',
        ];
    }
    
  3. Triggering Cascade Delete: Simply call delete() on the parent model:

    $parent = ParentModel::find(1);
    $parent->delete(); // Automatically deletes related polymorphic records
    

Implementation Patterns

Core Workflow

  1. Trait Integration:

    • Use the trait in models that own polymorphic relationships.
    • Explicitly list polymorphic methods in $cascadeDeleteMorph (string or array).
  2. Relationship Handling:

    • Supports morphOne, morphMany, and morphToMany (via morphTo).
    • Works with any model class linked via polymorphic associations.
  3. Conditional Cascading: Override the shouldCascadeDelete() method to add logic:

    protected function shouldCascadeDelete($relation)
    {
        return $this->isActive(); // Only cascade if model is active
    }
    

Advanced Patterns

  1. Dynamic Relationships: For dynamically defined relationships, use the cascadeDeleteMorph array with closure-based method names:

    protected $cascadeDeleteMorph = [
        'morphManyRelation',
        fn() => $this->dynamicMorphRelation(),
    ];
    
  2. Soft Deletes: Works seamlessly with Laravel’s soft deletes. Ensure related models also use SoftDeletes:

    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class RelatedModel extends Model
    {
        use SoftDeletes;
        // ...
    }
    
  3. Event Hooks: Extend the trait to add pre/post-cascade events:

    protected static function bootCascadeDelete()
    {
        static::deleting(function ($model) {
            Log::info("Cascading delete for {$model->id}");
        });
    }
    
  4. Bulk Operations: Cascade deletes work with Model::destroy() or Model::delete() on collections:

    ParentModel::where('status', 'inactive')->delete();
    

Gotchas and Tips

Common Pitfalls

  1. Missing Polymorphic Key: Ensure the related model has a parentable_id and parentable_type column. The package assumes standard Laravel polymorphic conventions.

  2. Circular Dependencies: Avoid cascading between models that reference each other polymorphically (e.g., A deletes B, which deletes A). This will cause infinite loops.

  3. Non-Polymorphic Relationships: The trait only works with polymorphic relationships. Attempting to cascade non-polymorphic relations (e.g., belongsTo, hasMany) will silently fail.

  4. Transaction Conflicts: If related models have database constraints (e.g., ON DELETE CASCADE), the package’s cascading may conflict. Disable native cascades or handle in a single transaction:

    DB::transaction(function () use ($parent) {
        $parent->delete();
    });
    

Debugging Tips

  1. Log Cascading: Enable query logging to verify cascades:

    DB::enableQueryLog();
    $parent->delete();
    dd(DB::getQueryLog());
    
  2. Check $cascadeDeleteMorph: Typos or incorrect method names will prevent cascading. Validate with:

    dd(get_class_methods($parent));
    
  3. Soft Delete Quirks: If soft deletes aren’t working, ensure:

    • The related model uses SoftDeletes.
    • The deleted_at column exists in the database.

Extension Points

  1. Custom Cascade Logic: Override the cascadeDelete() method to add custom logic:

    protected function cascadeDelete($relation)
    {
        if ($relation instanceof MorphMany) {
            $relation->each(fn($model) => $model->forceDelete());
        }
    }
    
  2. Exclude Specific Records: Filter records before deletion:

    protected function cascadeDelete($relation)
    {
        $relation->where('status', '!=', 'archived')->delete();
    }
    
  3. Performance Optimization: For large datasets, batch deletions:

    protected function cascadeDelete($relation)
    {
        $relation->cursor()->each->delete();
    }
    
  4. Custom Events: Dispatch events before/after cascading:

    protected function cascadeDelete($relation)
    {
        event(new CascadingDelete($relation));
        $relation->delete();
    }
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope