laravel 5 Changing database name in runtime

喜夏-厌秋 提交于 2019-12-24 00:54:07

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/35466362/laravel-5-changing-database-name-in-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!