1

I want to delete a record in category table wherein it will also delete the subcategory record which has a the foreign key of category. How can I do this?

Also, an explanation would help as why it has happened. Thank you!

Controller

public function destroy(Category $category)
{
    // return $category;
    Category::where('id', $category->id)->delete();
    Subcategory::where('category_id', $category->id)->delete();
    return back();
}

Category migration

Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });

Sub-category mgiration

Schema::create('subcategories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('category_id')->unsigned();
        $table->string('subcatname');
        $table->string('name');
        $table->timestamps();

        $table->foreign('category_id')->references('id')->on('categories');
    });
kwestionable
  • 496
  • 2
  • 8
  • 23

2 Answers2

2

this is simple because of the default delete: Restrict option in foreign key. 1.Add on delete cascade option to foreign key. This option will automatically remove any associated records from the subcategoires table when you delete the category record. The modified fk statement looks like as follows:

 ADD CONSTRAINT `category_subcategory_foreign` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`) ON DELETE CASCADE;

or you can go through

Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on a users table:

Schema::table('posts', function (Blueprint $table) {
$table->unsignedBigInteger('user_id');

$table->foreign('user_id')->references('id')->on('users');

});

You may also specify the desired action for the "on delete" and "on update" properties of the constraint:

$table->foreign('user_id')
  ->references('id')->on('users')
  ->onDelete('cascade');
1

You need onDelete method. Just from Docs

$table->foreign('category_id')
      ->references('id')->on('categories')
      ->onDelete('cascade');
aleksejjj
  • 1,715
  • 10
  • 21