6

Is there a modular way to perform cascading soft deletes in L4?

My database is already designed to do this with hard deletes because all tables are related to another.. however, I'm using soft deletes and really do not want to have to overload the delete() method in my models - simply due to (A) the amount of models, and (B) having to edit the delete() method in all models when other models change.

Any pointers or tips would be appreciated.

Rob W
  • 9,134
  • 1
  • 30
  • 50

2 Answers2

10

I've got cascading deletes working using model events, for example in a Product model I bind to the deleted event so I can soft-delete all relations:

    // Laravel's equivalent to calling the constructor on a model
    public static function boot()
    {
        // make the parent (Eloquent) boot method run
        parent::boot();    

        // cause a soft delete of a product to cascade to children so they are also soft deleted
        static::deleted(function($product)
        {
            $product->images()->delete();
            $product->descriptions()->delete();
            foreach($product->variants as $variant)
            {
                $variant->options()->delete();
                $variant->delete();
            }
        });
    }
robjmills
  • 18,438
  • 15
  • 77
  • 121
2

I do know this is possible from within my models:

public function delete() {
  ChildTable::where('parent_id', $this->id)->delete();
  ChildTable2::where('parent_id', $this->id)->delete();
  parent::delete();
}

But any update to models or table structure would cause this to be appended/edited.. including other models.

Rob W
  • 9,134
  • 1
  • 30
  • 50
  • Is this an answer or part of your question? – Wesley Murch Jun 21 '13 at 20:19
  • 1
    Both: It represents a way to cascade delete manually (or reassign parent tables child_id). However, a modular way of such delete would be nice; such as how Eloquent works with relationships. I mean.. the relationships are already there, so why not attempt to perform cascading soft deletes on the defined relationships? – Rob W Jun 21 '13 at 20:36
  • http://stackoverflow.com/a/14176326/3986937 as @Chris Schmitz pointed out you can add this behaviour in your migrations. – Logus Graphics Oct 24 '15 at 02:37