Inside of my AppServiceProvider I am attempting to hook onto the MigrationStarted event to modify the username and password to the admin user since the tenant user cannot alter tables.
public function boot()
{
foreach ([MigrationStarted::class, MigrationsStarted::class] as $event)
\Event::listen($event, $this->onAnyMigrationStarted(...));
}
private function onAnyMigrationStarted(MigrationStarted|MigrationsStarted $event): void
{
config()->set('database.connections.tenant.username', config('database.connections.gateway.username'));
config()->set('database.connections.tenant.password', config('database.connections.gateway.password'));
Schema::setConnection(DB::connection('tenant'));
}
However, if I dd(Schema::getConnection(), config('database.connections.tenant)) inside of the migration, I can see that the Schema connection is still using the tenant credentials yet the config is successfully updated.
Is there any way to force the Schema connection change in the AppServiceProvider without having to set this in all of the migration files?
Note: I don’t want the tenant connection to be the table owner or have access to modify tables, I just want to change the connection to the user role that can.
>Solution :
the MigrationsStarted event is fired after the migration process has already started, and changing the connection configuration at that point might not work as expected, I think you can use DB::purge() to clear the cache of connection, and then set the new configs you want to use to connect.
You can refer to the answered question here