Vaishnav Mhetre
Vaishnav Mhetre

Reputation: 199

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.

eg.

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

Upvotes: 3

Views: 1432

Answers (2)

JasonK
JasonK

Reputation: 5294

You could save database connection(s) for each user in a "central" database. Query that database, find the matching connection parameters and use them to query the user's database.

Multi-tenant applications use a similar approach. I've created a package to craft multi-tenant applications with Laravel. This package requires 'tenants' to be defined in a config file... which you do not want. Take a look at the source code tho. It might help you bring up new ideas.

Upvotes: 1

Moppo
Moppo

Reputation: 19275

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

Config::set('database.connections.DB1.test1', 'test2');

Upvotes: 3

Related Questions