Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ravipw1801's avatar

Cascade deleting with Polymorphic relationship

3 types of posts Business, Social & Nature. All these have some attributes in common Country, City & Range. These common attributes have polymorphic relation with all three types of postscountriable, citiable & rangeable.

BusinessPosts table structure:

public function up()
    {
        Schema::create('businesses', function (Blueprint $table) {
            $table->increments('id');
            $table->string('brand');
            $table->integer('user_id')->unsigned();
            $table->integer('phone');
            $table->string('email');
            $table->string('url');
            $table->text('description')->nullable();
            $table->tinyInteger('status')->default(0);
            $table->timestamps();
        });
    }

BusinesPost Model:

class BusinessPost extends Model
{

    public function ranges()
    {
        return $this->morphToMany('App\Range','rangeable');
    }

    public function countries()
    {
        return $this->morphToMany('App\Country','countriable');
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }

}

Country Model:

class Country extends Model
{
    protected $fillable = ['name'];

    public function businesses()
    {
        return $this->morphedByMany('App\Business', 'countriable');
    }

    public function socials()
    {
        return $this->morphedByMany('App\Social', 'countriable');
    }

    public function natures()
    {
        return $this->morphedByMany('App\Nature', 'countriable');
    }
}

country table structure:

public function up()
    {
        Schema::create('countries', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }

countriable table structure:

public function up()
    {
        Schema::create('countriables', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('country_id');
            $table->integer('countriable_id');
            $table->string('countriable_type');
            $table->timestamps();
        });
    }

So, my question is, if the user deletes a post, all of its relationships should get detached, or in case the user deletes its account, all his posts, along with relationships should get deleted?

Till now everything is working fine except the deletion part!

0 likes
6 replies
ravipw1801's avatar

Hi @Tray2 I know cascade deleting with one to one or one to many, but how this will work in polymorphic relationship?

Please or to participate in this conversation.