0

I can't delete a category because it is a foreign key in the items table. How can I do it? How can I make a deletion in category and make $category_id null in the items table?

I tried making a delete function but it sends an error saying it can't because it is a foreign key.

jancalimbo
  • 15
  • 4

2 Answers2

1

Create a migration to allow the field category_id to have null value and to default to null when the referenced category is deleted by setting onDelete null on foreign key

$table->foreignId('category_id')->nullable()->constrained()->onDelete('set null');

You can also read from here

Official Docs

N69S
  • 16,110
  • 3
  • 22
  • 36
Khayam Khan
  • 197
  • 12
-1
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
// write your delete code here
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
Ashutosh Jha
  • 144
  • 4
  • 2
    Please don't just dump two lines of code as an answer! Add some explanation of why that code would work etc. so others can learn. Thanks – brombeer Nov 08 '22 at 07:17
  • Sorry. It will disable foreign key constrain for the code inside the block. public function deleteCategory(Category $category){ DB::statement('SET FOREIGN_KEY_CHECKS=0;'); $categoru->delete(); //Now you can enable the foreign key constrain DB::statement('SET FOREIGN_KEY_CHECKS=1;'); } – Ashutosh Jha Nov 08 '22 at 07:22
  • 1
    at the expense of database integrity. You will end up with entries referencing categories that doesn't exist and create more bugs down the line. and now even if there is a category_id value in the entry you need to check for its existance in the categories table. good job, you're making your life harder. – N69S Nov 08 '22 at 08:21
  • You can write the logic for that inside your function. DB::statement('SET FOREIGN_KEY_CHECKS=1;'); It will enable the foreign key to constrain again. If a product can't exist without a category then you should delete the product too. Or you can set the category_id to 0. Your problem was due to constraining you are not unable to delete. Thats what I have suggested this path but you have to think the logic yourself – Ashutosh Jha Nov 08 '22 at 11:48
  • 3
    The explanation belongs in your answer, not buried in comments. Edit your answer to add information. – Blastfurnace Nov 09 '22 at 00:58