Dealing with no migrations in a Laravel project

I have inherited some Laravel projects where the migration files were outdated or nonexistent. This makes setting up local development or staging environments, or writing automated tests, very challenging. After encountering a couple of Laravel projects with this issue, I found myself repeating the same steps to solve this.
Firstly, we need two backups of our production database. One is a complete mirror of your existing database, and the other should have only the data in the tables and no information about the table schema. The data-only backup will be used to test the generated migration files. I will refer to the first as backup-1and the second, backup-2.
Next, we will create a database in our local environment and import backup-1. After that, we can install this awesome package. I used to write the migration files by hand, and it was error-prone and very time-consuming. This package saves us hours, especially when the project has many tables. After installing the package, run the command below to generate the migrations for the existing files.
php artisan migration:generate --ignore-tables=migrations
I don’t generate the schema of the migration table because I prefer sticking to the default that Laravel ships with. Also, I avoid generating schemas for 3rd party packages. I prefer to publish their migration files.
Next, create a new database and change the database configuration in our local environment to point to it and run the php artisan migratecommand. Now we are at the moment of truth. Disable foreign checks and import backup-2into the database. If everything worked, you should get no errors in the import log. At this point, the migration files and table schemas are in sync.
Things to note
Since the tables already exist in the production database, you will get an error if you try to run
php artisan migrateduring your next deployment. You need to add a condition to skip creating or modifying the table if it already exists. Eg.If(Schema::hasTable('users')){ ...}Since you are using a backup of your production database, you should ensure you don’t inadvertently send notifications to your users’ email or phone numbers. It might be best to anonymise the data before you import it locally.



