Search code examples
laravelforeign-keysmigrationcascading-deletes

Laravel adding cascade on delete to an existing table


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


Solution

  • 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