Home > Blockchain >  Laravel onDelete('cascade') does not work
Laravel onDelete('cascade') does not work

Time:04-07

My Tables:

 Schema::create('support_categories', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->string('slug')->nullable();
        $table->timestamps();
    });
Schema::create('supports', function (Blueprint $table) {
        $table->id();
        $table->foreignId('support_category_id')->onDelete('cascade')->constrained('support_categories')->nullable();
        $table->string('title');
        $table->string('slug');
        $table->timestamps();
    });

I am getting following errors when I try to delete support_categories

Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails

CodePudding user response:

You just write foreign key in wrong order.

Instead of:

$table->foreignId('support_category_id')->onDelete('cascade')->constrained('support_categories')->nullable();

Write:

$table->foreignId('support_category_id')->nullable()->constrained('support_categories')->onDelete('cascade');

or you can use casadeOnDelete():

$table->foreignId('support_category_id')->nullable()->constrained('support_categories')->casadeOnDelete();
  • Related