Sunny Kumar
Sunny Kumar

Reputation: 544

Laravel 8 Change database connection globally in the runtime

My requirement is pretty simple and I found a lot of solutions, but none of them is working for me.

I have two MySQL databases, one where all write operations will happen and there is a replica of this database, which is read-only. I am creating a middleware where if a request is GET, it should use read-only database otherwise main databases.

I already have tried these:

DB::disconnect();
Config::set('database.default', 'mysql_readonly');
DB::reconnect('mysql_readonly');


Config::set('database.default', 'mysql_readonly');
DB::purge('mysql_readonly');


DB::disconnect();
Config::set('database.default', 'mysql_readonly');
DB::connection('mysql_readonly');

None of the solutions is working.

Upvotes: 0

Views: 1852

Answers (1)

Sunny Kumar
Sunny Kumar

Reputation: 544

I found the working solution.

$readOnlyConfig = config('database.connections.mysql_readonly');
Config::set('database.connections.mysql', $readOnlyConfig);
DB::purge();

Upvotes: 1

Related Questions