Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to override the Schema connection details during migrations in Laravel 10.x

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading