Skip to content
Advertisement

When is the configuration initialized for a Laravel application? or when DB::connection is set?

I have a Middleware that changes a database config dynamically like this:

config(['database.connections.mysql.database'=> 'newDatabaseName']);

And in each model, I have $connection = 'mysql' explicitly set.

Inside of my model constructor:

logger()->info(get_class($this). ' database: ' . config('database.connections.mysql.database'));
logger()->info(get_class($this). ' database: ' . DB::connection($this->connection)->getDatabaseName());

The output is:

newDatabaseName
oldDatabaseName

where newDatabaseName is the database I set in the middleware and oldDatabasename is the .env database name.

So basically I successfully set the database name in the configuration, but the model is still using the .env database name for some reason.

Any ideas why this happens?

I have other middlewares applied to these routes:

SubstituteBindings::class,
ChangeLocale::class,
HandleCors::class,

I thought it was because of the “SubstituteBinding” middleware, but I have tried to put my middleware before and after it, it doesn’t make a difference.

I’m using laravel 5.6

Advertisement

Answer

I finally found what’s going on. DatabaseManager caches all the connections for the first time, this will fix it:

config(['database.connections.mysql.database' => 'newDatabaseName']);

DB::purge('mysql');

DB::reconnect('mysql');

Here is the post I found that talks about the exact problem: https://divinglaravel.com/understanding-how-laravel-configures-database-connections

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement