Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 5 Changing database name in runtime

is there a way to change the database name of a connection instead of adding another? It's okay if I add 3 or 5 databases in Config.database.connections, but what If I have 100 or more databases I am working with? Since all use the same HOST, USERNAME and PASSWORD, is there anyway to just change the database name dynamically and work with that during the whole session? I tried

Config::set('database.connections.mysql.database', 'database1');

but when I try using queries , it still uses the default one.

like image 346
JCD Avatar asked Feb 17 '16 19:02

JCD


2 Answers

If anyone still is searching for the answer for this question, answer is here:

You can change database name(not connection) at run time as follows:

Import following classes on top of your controller or middleware:

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

Then inside function, change database name as follows:

DB::disconnect('mysql');//here connection name, I used mysql for example
Config::set('database.connections.mysql.database', $dbName);//new database name, you want to connect to.

After this whenever you will make query to extract any data from any table, it will search into new database provided.

Please note, this is for changing database name in SAME connection while runtime.

I hope it helps

like image 85
Abhay Maurya Avatar answered Nov 17 '22 18:11

Abhay Maurya


In my case using Laravel 6 disconnecting and setting alone did not work.
I still had to reconnect the database like so:

 \DB::disconnect('mysql'); 
 \Config::set('database.connections.mysql.database', $database_name);
 \DB::reconnect();

More about the case can be found here Laravel 6 config()->get('database.connections.mysql') not matching DB:connection()

like image 1
leopold Avatar answered Nov 17 '22 19:11

leopold