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
Answer
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
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms