1

In my laravel application I have a table called researces and another one called papers. They have one-to-many relationship where each research can have one or more papers. In papers migration file I created the foreignkey constraints using:

        //foreign key for the research model
        $table->unsignedBigInteger('research_id');
        $table->index('researach_id');

Now I want to create a new migration to add cascade onDelete so that papers are deleted when their parent research is deleted. How do I do it? I'm using laravel 5.1

EDIT

SO the answer is very similar to the one accepted, except that I had to delete the column first and then add the foreign key. since I'm not in the production yet, so dropping the column is not a problem but if you are in a production environment you could end up messing with the consistency of data in your database. so be careful

2 Answers 2

5

Drop foreign key first then add it

$table->dropIndex('researach_id');
$table->foreign('research_id')
->references('id')->on('researches')
->onDelete('cascade');

Reference: Laravel -> Database: Migrations -> Foreign Key Constraints

8
  • Thanks. The problem is when i try to drop it I get Syntax error or access violation: 1091 Can't DROP FOREIGN KEY research_id; check that it exists (SQL: alter table papers drop foreign key research_id)
    – marmahan
    Feb 21, 2020 at 9:47
  • Thanks. Now I get this error 1091 Can't DROP FOREIGN KEY papers_research_id_index; check that it exists (SQL: alter table papers drop foreign key research_id)
    – marmahan
    Feb 21, 2020 at 10:54
  • can't I simply do $table->dropcolumn('research_id');?
    – marmahan
    Feb 21, 2020 at 10:55
  • Yes you can do that but then you have to create that column again
    – Sehdev
    Feb 21, 2020 at 10:57
  • You are getting this error because you did not create a Foreign key index. You just created a normal index using $table->index('researach_id');
    – Sehdev
    Feb 21, 2020 at 11:00
1

Create a new migration and add the necessary foreign key constraints and also operations to be performed when the foreign key data is modified/deleted.

$table->foreign('research_id')
      ->references('id')->on('researches')
      ->onDelete('cascade');

Documentation can be found here.

2
  • So that means I have to delete this column first, then adding it as you wrote? I tried to do it but got this: Syntax error or access violation: 1091 Can't DROP FOREIGN KEY research_id; check that it exists (SQL: alter table papers drop foreign key research_id)
    – marmahan
    Feb 21, 2020 at 9:46
  • Yes, you do need to drop the column if there were previous foreign key constraints set.
    – tamrat
    Feb 21, 2020 at 9:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.