3

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

2
  • Why do you have multiple databases? Commented Jul 8, 2016 at 12:41
  • I'm working over single framework for multiple organizations, hence the data for each organization needs to be stored in distinct database. Commented Mar 2, 2017 at 9:13

2 Answers 2

3

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

Config::set('database.connections.DB1.test1', 'test2');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That may help though.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.