Change the Database Connection Dynamically in Laravel

tyro picture tyro · Oct 16, 2017 · Viewed 11.7k times · Source

I have the master database with login table and corresponding database settings for each user. On login I should dynamically change the db settings fetching from the table. I can change the db connection but this is not persisting.

Config::set("database.connections.mysql", [
'driver' => 'mysql',
"host" => $usr_host,
"database" => $usr_database,
"username" => $usr_username,
"password" => $usr_password,
...
]);

edit: New database is created for each user when he/she registers with the app and thus i dont have the database connection for each user defined in the config/database.php

Answer

Adam Kozlowski picture Adam Kozlowski · Sep 25, 2018

This way you can set new parameter when it comes to database:

 \Config::set('database.connections.mysql.database', $schemaName);

Remember about PURGE to persist this settings

 DB::purge('mysql');

Cheers!