Home > Back-end >  How to use Cascade Soft Delete Trait in laravel 8?
How to use Cascade Soft Delete Trait in laravel 8?

Time:12-02

$inst = Institution::find($institution->id); $campus = InstitutionCampusId::where('institution_campus_id.institution_id' , $institution->id); $inst->delete(); $campus->delete();

CodePudding user response:

add this trait in your model

use SoftDeletes;

add this in your migration it will add deleted at field in your table

$table->softDeletes();

CodePudding user response:

Cascading deletes are handled at the database-level, so when you set onDelete('cascade') in your migration, that translates to your database deleting any records attached by foreign key.

Soft deletes are handled by the application, so you'd either need to fire an event on the parent model and listen for it on the children or, in your parent model, bind the static::deleted() method in the boot method, and delete the relationships there.

I'm not sure if you could do something like:

public static function boot()
{
    parent::boot();

    static::deleted(function ($model) {
        // Probably lazy load these relationships to avoid lots of queries?
        $model->load([ 'relationshipOne', 'relationshipTwo', ]);

        $model->relationshipOne()->delete();
        $model->relationshipTwo()->delete();
    });
}

Or if you'd have to iterate over the related items:

public static function boot()
{
    parent::boot();

    static::deleted(function ($model) {
        $model->relationshipOne->each(function ($item) {
            $item->delete();
        });

        $model->relationshipTwo->each(function ($item) {
            $item->delete();
        });
    });
}

CodePudding user response:

Add trait to your model use SoftDeletes; and on your migration add $table->softDeletes() on the end of the schema creation (this be automatically create deleted_at column)

And for query you can use eloquent methods to get only deleted or without deleted entries, example:

To get only deleted entries: $query->onlyTrashed(),

To get only non deleted entries: $query->withoutTrashed(),

To get all entries (with deleted): $query->withTrashed()

To send entry in trash use: $model->delete(),

For permanently delete entry use: $model->forceDelete()

  • Related