Is the sower working great for the first time, but doesn't perform some tasks in subsequent cycles in Laravel 5?

I work on several applications with several databases, where I have a main one DB, which consists of a table of tenants, and then a new one is created for each tenant created DB. I write a seed file for this, and I run it 3 times to create 3 Tenants and the next 3 DBfor them.

It works great for the first time. A new tenant is created mainly DB. A new one DBis created using a usernamenew tenant. DBalso migratedwith a command call Artisanfrom code. But in the next two cycles, tenants are created mainly DB, and a new one is also created for them DB, but the command call Artisandoes not transfer DB.

public function run()
{
    $faker = Faker::create();

    // Fetching all tenants
    $tenants = App\Tenant::all();

    // Deleting their databases
    $tenants->each(function($tenant){
        DB::statement('DROP DATABASE IF EXISTS ' . $tenant->username);
    });

    // Truncating the tenants table itself
    DB::table('tenant')->truncate();

    for($i = 0; $i < 3; $i++){

        $company = $faker->company();
        $description = $faker->text();
        $logo = $faker->imageUrl(50, 50);
        $username = str_random(8);

        \Config::set('database.default', 'archive');

        echo 'Creating tenant ' . $i . "\r\n";

        Tenant::create([
            'name'          => $company,
            'description'   => $description,
            'logo'          => $logo,
            'username'      => $username,
        ]);

        DB::statement('CREATE DATABASE ' . $username);

        \Config::set('database.connections.tenant.database', $username);
        \Config::set('database.default', 'tenant');

        echo 'Migrating tenant ' . $i . "\r\n";

        \Artisan::call('migrate', [
            '--path' => 'database/migrations/tenants'
        ]);

        echo "\r\n";
    }
}

What am I doing wrong here. It works great for the first time. And then the last two times are created only DB, but not transferred. Only the first has been successfully transferred from this DB. And no mistake is thrown from the artisan.

The command line output is as follows:

Creating tenant 0

Migrating tenant 0


Creating tenant 1

Migrating tenant 1


Creating tenant 2

Migrating tenant 2
+2
source share
1

Laravel, , config . DB::connection($connection)->reconnect().

, Laravel migrations, .

:

# ...
\Config::set('database.connections.tenant.database', $username);
\Config::set('database.default', 'tenant');

\DB::reconnect();
\DB::setDatabaseName($username);
# ...
+2

Source: https://habr.com/ru/post/1610896/


All Articles