Change The Database Connection Dynamically In Laravel
Answer :
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!
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
you need to get the config first.. then alter the specific field then set it back..
$config = Config::get('database.connections.company'); $config['database'] = "company_tenant_$id"; $config['password'] = "test2123"; config()->set('database.connections.company', $config);
Comments
Post a Comment