Skip to content
Advertisement

Use one Laravel migrations table per database

I work in a project that uses multiple databases. It seems like Laravel only uses the migrations-table in the database that is set as default. I would like one migrations table per database that logs the migrations that have been done to that specific database. Is this possible?

I have defined the databases in the config like this:

JavaScript

I also made the first database (db1) the default one

JavaScript

I install the migrations table on both databases

JavaScript

After that i proceed to create a couple of database specifc migrations

Create table test1 in db1 database:

JavaScript

Create table test2 in db2 database:

JavaScript

I now run the migrations

JavaScript

Expected outcome

db1.migrations

JavaScript

db2.migrations

JavaScript

Actual outcome

db1.migrations

JavaScript

db2.migrations

JavaScript

Advertisement

Answer

Article on usage of multiple database usage in Laravel – https://stackcoder.in/posts/laravel-7x-multiple-database-connections-migrations-relationships-querying

Use the --database parameter with the migrate command and store the migrations for each database in separate directories.

You could have separate directories in app/database/migrations for each of your database (in your case db1 and db2) and store the appropriate migrations in each directory. Then you could run the migrations like this:

JavaScript

This way your migrations table will be independent for each database.

If you want to go the extra mile and automate the process you could create your custom command that will run all the migrations at once. You can create the command like this (use make:console for Laravel 5.0 up to 5.2 or make:command for Laravel 5.2+):

JavaScript

This will create a new file app/commands/MigrateAllCommand.php. Your command’s fire method would look something like this:

JavaScript

This will work provided the name of the database configuration key is the same as the migration directory name. You can then just call it like this:

JavaScript

You can check the Laravel Command Docs for more info.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement