skip to Main Content

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.

2

Answers


  1. DB::statement('SET FOREIGN_KEY_CHECKS=0;');
    // write your delete code here
    DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search