Блог Серії
Кар'єра
Вакансії Компанії
Навчання
Співбесіди Тестування Відео
Екосистема
Пакети Ресурси Проєкти
Інше
Події Про нас

Laravel Cascade Soft Deletes

michaeldyrynda/laravel-cascade-soft-deletes
4.6.1 1,178 3.6M 20 березня 2026 2
На GitHub

Пакет забезпечує каскадне видалення для Eloquent-моделей, які використовують soft deletes, автоматично видаляючи пов'язані записи при видаленні батьківської моделі.

Поділитись

README

Cascading soft deletes for the Laravel PHP Framework

Build Status Latest Stable Version Total Downloads License Buy us a tree

Introduction

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.

Code Samples

<?php

namespace App;

use App\Comment;
use Dyrynda\Database\Support\CascadeSoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Post extends Model
{
    use SoftDeletes, CascadeSoftDeletes;

    protected $cascadeDeletes = ['comments'];

    protected $dates = ['deleted_at'];

    protected $fetchMethod = 'get'; // get, cursor, lazy or chunk
    // protected $chunkSize = 500;

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

Now you can delete an App\Post record, and any associated App\Comment records will be deleted. If the App\Comment record implements the CascadeSoftDeletes trait as well, it's children will also be deleted and so on.

$post = App\Post::find($postId)
$post->delete(); // Soft delete the post, which will also trigger the delete() method on any comments and their children.

Note: It's important to know that when you cascade your soft deleted child records, there is no way to know which were deleted by the cascading operation, and which were deleted prior to that. This means that when you restore the blog post, the associated comments will not be.

Because this trait hooks into the deleting Eloquent model event, we can prevent the parent record from being deleted as well as any child records, if any exception is triggered. A LogicException will be triggered if the model does not use the Illuminate\Database\Eloquent\SoftDeletes trait, or if any of the defined cascadeDeletes relationships do not exist, or do not return an instance of Illuminate\Database\Eloquent\Relations\Relation.

Installation

This trait is installed via Composer. To install, simply add to your composer.json file:

$ composer require dyrynda/laravel-cascade-soft-deletes

Support

If you are having general issues with this package, feel free to contact me on Twitter.

If you believe you have found an issue, please report it using the GitHub issue tracker, or better yet, fork the repository and submit a pull request.

If you're using this package, I'd love to hear your thoughts. Thanks!

Treeware

You're free to use this package, but if it makes it to your production environment you are required to buy the world a tree.

It’s now common knowledge that one of the best tools to tackle the climate crisis and keep our temperatures from rising above 1.5C is to plant trees. If you support this package and contribute to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats.

You can buy trees here

Read more about Treeware at treeware.earth

Коментарі

Увійдіть, щоб залишити коментар

Будьте першим, хто залишить коментар!

Схожі пакети

Laravel Query Builder

spatie/laravel-query-builder

Легко будуйте Eloquent-запити на основі запитів від API.

4,455 7.3.0 13 7

Eloquent Sluggable

cviebrock/eloquent-sluggable

Легке створення слагів для ваших моделей Eloquent у Laravel.

3,993 13.0.0 13 36

Laravel Auditing

owen-it/laravel-auditing

Пакет для аудиту змін Eloquent моделей у Laravel, що дозволяє автоматично відстежувати та записувати всі модифікації даних.

3,440 v14.0.6 13 5

Sushi

calebporzio/sushi

Додатковий драйвер для Eloquent, який дозволяє працювати з масивами даних як з повноцінними Eloquent моделями.

3,005 v2.5.4 13 8

Iseed

orangehill/iseed

Генерує новий файл seed для Laravel на основі даних з існуючої таблиці бази даних.

2,896 v3.8.1 13 4

Eloquent Has Many Deep

staudenmeir/eloquent-has-many-deep

Laravel Eloquent відносини HasManyThrough з необмеженою кількістю рівнів вкладеності.

2,861 v1.22.1 5