'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
Solution 1:[1]
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mirafzal Shavkatov |
