Skip to content
Advertisement

Laravel onDelete(‘cascade’) does not work

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

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement