Have you ever felt drawn in tons of Laravel database migration files?
I think we all following the same approach when updating an existing table making any new change in a brand new migration file.
After months of development, I am sure it ends with tons of migration files and you can’t figure out the full schema of the table you have to go through each update file or you could make yourself a favor and check the table structure directly using some database clients like TablePlus or Sequel Pro or whatever client you are using.
In my last project I followed an approach and I think it works well and I thought to share it with you.
First, at the first development phase where we are still tinkering and editing the database structure regularly, why we need to add more files?
till now there is no real data only some fake data for testing purposes and if there are some real data they are saved in sql in seeded every time running the seed command.
so during this phase we were editing the migrating files themselves and every time there is a change we safely run
php artisan migrate:refresh --seed` command.
At some points of development, there is a need to make a staging server for the client to view the project and the client inserts some real data.
Here we don’t make him loose the data so he can continue his work without interruption.
Here comes the idea of making temporary files (scripts) for running the new migration updates
As show in the previous Image here we are making two changes:
1- Update the main migration file (right window)
2- Add the new changes “with checking if the change not exists first” (left window)
With this Approach I think it’s a win win situation
php artisan migrate on the staging server will run the new temporary file (left window) and we will not loose the data.
Also developers can run
php artisan migrate:fresh --seed safely in their local environment here the 2 files will be executed but with the conditions added in this file the statements will not run again and we will not have the (bla bla is already exists) error again.