generate migrations from an existing database in Laravel

To create a Laravel migration file from an existing MySQL database, follow these steps:


1. Install laravel-migrations-generator package

Since Laravel does not generate migrations from an existing database by default, use a third-party package:

composer require --dev kitloong/laravel-migrations-generator

2. Generate Migrations

Run the following command to generate migration files from your MySQL database:

php artisan migrate:generate

This will create migration files for all tables in the database/migrations directory.


3. Generate Migrations for a Specific Table

If you only want to generate migrations for a specific table, use:

php artisan migrate:generate --tables=your_table_name

For multiple tables:

php artisan migrate:generate --tables=table1,table2,table3

4. Handle Foreign Keys

If your database has foreign keys, ensure they are properly referenced in the migration files.

To include foreign keys in the migration generation, use:

php artisan migrate:generate --fk

5. Verify & Modify the Generated Migrations

  • Open the migration files in database/migrations/
  • Ensure all table structures and constraints are correctly defined
  • Adjust column types or add missing constraints if needed

6. Run Migrations in a New Database

Once migrations are generated, you can use them to set up a new database:

php artisan migrate

Alternative Method Using laravel-schema-spy

If you prefer another tool, you can also use laravel-schema-spy:

composer require --dev beyondcode/laravel-er-diagram-generator
php artisan generate:erd

Would you like help with generating seeders or factory files as well? 🚀

Leave a Reply

Your email address will not be published. Required fields are marked *