I am working on a multi tenant multi database application where I have a main DB
which consists of a tenant table and then for each tenant that is created, there is
The database connection is kept alive in Laravel, which means that it will not switch to new database when you change the database name via config
. You need to force the background connection to be reconnected by DB::connection($connection)->reconnect()
.
When running migrations, because Laravel use the database name and the table name to check the existence of the migrations
table, you need to update the table name of the current connection as well.
In your case:
# ...
\Config::set('database.connections.tenant.database', $username);
\Config::set('database.default', 'tenant');
\DB::reconnect();
\DB::setDatabaseName($username);
# ...