This package permit add a trait for use in Elocuents Models that deletes in
cascade the Polymorphic Relations (MorphOne, MorphMany or MorphToMany).
This package can be used in Laravel 5.5 or higher.
You can install the package via composer:
composer require cesargb/laravel-cascade-deleteUse the trait Cesargb\Database\Support\CascadeDelete in your Elocuent Model and define de property cascadeDeleteMorph whith one String or Array with your methods than define the Polymorphic Relations.
<?php
namespace App;
use App\Tag;
use App\Image;
use App\Option;
use Illuminate\Database\Eloquent\Model;
use Cesargb\Database\Support\CascadeDelete;
class Video extends Model
{
use CascadeDelete;
protected $cascadeDeleteMorph = ['image', 'tags', 'options'];
public function image()
{
return $this->morphOne(Image::class, 'imageable');
}
public function options()
{
return $this->morphMany(Option::class, 'optionable');
}
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
}Now you can delete an App\Video record, and any associated App\Image, App\Options and pivot records for
App\Tag will be deleted.
If you bulk delete a model with morphological relationships, you will have residual data that has not been deleted.
To clean this waste you have the method deleteMorphResidual
Sample:
Video::query()->delete();
$video = new Video;
$video->deleteMorphResidual();You can use Artisan command morph:clean to remove all residuals data from all
your Moldes that used the Cesargb\Database\Support\CascadeDelete trait.
php artisan morph:cleanAny contributions are welcome.