Search code examples
phpmysqldatabaselaravelmulti-tenant

Change the Database Connection Dynamically in Laravel


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


Solution

  • Well you can use the default database for user login and have a new field for the database name. Then whenever you need to query a different database, you can just change your db connection.

    Something like this

    $someModel = new SomeModel;
    $databaseName = "mysql2"; // Dynamically get this value from db
    $someModel->setConnection($databaseName);
    $something = $someModel->find(1);
    

    You can read more about it here. http://fideloper.com/laravel-multiple-database-connections