Vaishnav Mhetre Vaishnav Mhetre - 1 year ago 54
PHP Question

Change Database of existing Database Connection - Laravel

I recently got to know about the Laravel Framework which is awesome but just want to know one query which is still a mystery for me.

I know we can easily change the "Database Connection" using

$users = DB::connection('mysql2')->select(...);

but I'm working on such a project where Multiple Databases are created as per user request and need to access these databases dynamically as per user request.

Its nearly impossible to enter every database entry as new database connection entry in Database config file.

Hence I need a way to change the Database dynamically in the same connection we are using.


If we are using "DB1" connection with Database "test1" as defined in config file,

I need a way to change the "test1" database to "test2" DYNAMICALLY

Answer Source

Probably you can do that by simply changing the value of the database configuration at runtime:

Config::set('database.connections.DB1.test1', 'test2');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download