4

Hi i have been searching over the internet regarding using multiple database connections and found solutions that allows me to first create connection in database.php and then i can switch them whenever needed. Now the problem is i dont know about the database names on run time. I have a primary database for letting user login and then the database will determine which database to switch based on user log in.

What i have tried :

Config::set('database.connections.mysql.database', Config::get('database.connections.mysql.database') . '_business_' . $preUser->business_id);

This is what i did earlier and my code was working on local environment but when i switched to my dev environment it stopped working.

Any idea why

The other issue i am getting is i want to run migrations and seeding with this same scenario. I would have a series of databases in an array and will need to run migration on each of them.

I have also tried this solution but it does not work somehow. it shows null when i try to get my database connection after setting it

Laravel: connect to databases dynamically

1
  • For the migration part is most likely that your Config::set part is not being called as that is going through artisan. You can extend artisan or run the migrations through your code. Like > Artisan::call('migrate', ['--path' => '../plugins/'.$tag.'/migrations', '--force' => true]); Commented Jul 14, 2017 at 6:32

1 Answer 1

0

Regarding your topic question - it can be done by creating new temporary database connection in configuration and using it to connect new database:

Config::set("database.connections.$database", $newDBConnectionParams);
$this->connection = DB::connection($database);

This approach is described here

As to your code working on local environment but do not working on dev - I suspect this is because of the config cache - when you try to update existing config entry, it won't update because entry value is taken from cache. And it seems that config cache has different settings on local and dev environment.

Sign up to request clarification or add additional context in comments.

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.