Laravel Packages / updated: July 19, 2016

Cascading soft deletes with Eloquent

Michael Dyrynda has a new package for cascading soft deletes with Laravel and Eloquent.

In scenarios when you delete a parent record – say for example a blog post – you may want to also delete any comments associated with it as a form of self-maintenance of your data.

Normally, you would use your database’s foreign key constraints, adding an ON DELETE CASCADE rule to the foreign key constraint in your comments table.

It may be useful to be able to restore a parent record after it was deleted. In those instances, you may reach for Laravel’s soft deleting functionality.

In doing so, however, you lose the ability to use the cascading delete functionality that your database would otherwise provide. That is where this package aims to bridge the gap in functionality when using the SoftDeletes trait.

Here is some example code:

class Post extends Model
{
    use SoftDeletes, CascadeSoftDeletes;

    protected $cascadeDeletes = ['comments'];

    protected $dates = ['deleted_at'];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}    

It’s simple to setup and if you are in need of cascading soft deletes, check it out.

Laravel News Partners

Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.