Best way to handle multi-table Laravel migrations that failed halfway through?

340 views Asked by At

Originally I wanted to use an array to keep track of image paths of product shots. I decided to replace this column with a separate 'images' table that references my 'inventory' table. This allows me to use the auto-incrementing 'image' 'id' as part of the image name in order to ensure uniqueness.

I made a migration that dropped the 'image_paths' column and then created a new 'images' table with various columns. I had a typo in the second part of the migration where I defined the new table. When I ran the migration it failed, but the 'image_paths' column was deleted. So I can't roll back because the migration was never registered. I also can't run the migration again because it will try to drop a column that doesn't exist.

Is my best bet to manually add the 'image_paths' column back in and then run the migration? Should I avoid making changes to multiple tables per migration from now on?

2

There are 2 answers

0
Ray On
  1. the best way to do it is to back up your db entries. There could be multiple fatal errors during your migration.

  2. When you changes the column in a specific table, make sure you add everything first and then delete or remove the columns you do not want. Because removal is a rather dangerous move, you need to make sure it is done after other possible operations are done.

  3. To further decrease the risk, you may want to separate multiple operations in different migration files. Make sure each operation is finished successfully and then move on to the next one.

Follow these rules and everything should be just fine.

0
Pete Houston On

Here my suggestions,

  1. There are basically two methods up() and down(); Remember to implement the down() along with the up(), for when you have problem with artisan migrate which calls up(), you will need to rollback your schema with artisan migrate:rollback which calls down().

  2. Separate into many migrations as one per job; similar to Single Responsibility Principle. For example, if you need to drop a column, create a new table, making a new foreign key for relationships, then make at least 3 migrations.

  3. Never make migrations run directly on production without testing on local and staging. For local and staging, there is no need for data backup because you have Seeder (local, staging) or production_data.sql (staging). If the migrations are running without any problem on local and staging machine, then it should be OK for production environment. Make sure to NEVER EDIT/UPDATE the migrations on production environment, you will have yourselves killed.

Those are what I do, and haven't met any problem with migrations.