Ian
Ian

Reputation: 3676

Migrating multiple databases with Laravel Artisan

I have my command migrate:s which contains the following

public function handle()
{

    $sites = Sites::all();


    foreach($sites as $site)
    {
        $host       = $site->h;
        $database   = $site->d;
        $username   = $site->u;
        $password   = $site->p;

        $this->info('Trying to migrate ' . $database);

        Config::set('database.connections.mysql.host',      $host);
        Config::set('database.connections.mysql.database',  $database);
        Config::set('database.connections.mysql.username',  $username);
        Config::set('database.connections.mysql.password',  $password);

        //Reconnect with new credentials
        DB::reconnect('mysql');

        //Call the migration on the new connection
        $this->call('migrate');

        $this->info('Migrations complete for database ' . $site->d);
    }
}

The first site always migrates fine, however after it keeps trying to create the migration table despite there already being one, one that is populated.

SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'migrations' already exists

The credentials are correct for the databases, I cannot figure out why it's trying to make the table after the first migration.

Upvotes: 2

Views: 912

Answers (2)

Ian
Ian

Reputation: 3676

The issue is that the settings were being cached, hence the first connection working, so you need to purge the connection by using

DB::purge('connectionName');

Upvotes: 3

Loren
Loren

Reputation: 12711

Just a thought, it may be that the ->call function somehow reinitializes part of Laravel, or at least that's my best guess. If you have each site as a database connection (ie mysql1, mysql2, mysql3, etc), you might try using the --database option for migrate to run the migration and see if that helps?

The migrate command has an option for picking the database connection:

https://github.com/laravel/framework/blob/5.1/src/Illuminate/Database/Console/Migrations/MigrateCommand.php

Upvotes: 1

Related Questions