Laravel,如何在config/database.php文件中添加新连接?
我的目标是在我通过Laravel,如何在config/database.php文件中添加新连接?,php,laravel,Php,Laravel,我的目标是在我通过DB::statement 还有一个类似的问题,但问题是它是在config/database.php中预定义的 web.php(路由) config/database.php 希望看到它像下面这样动态编辑。但是我不知道如何在不手动编辑实际文件的情况下进行操作。假设驱动程序、主机、端口、用户名和密码相同 'testDB' => [ 'driver' => 'mysql', 'host' => 'localhost'
DB::statement
还有一个类似的问题,但问题是它是在config/database.php中预定义的
web.php(路由)
config/database.php
希望看到它像下面这样动态编辑。但是我不知道如何在不手动编辑实际文件的情况下进行操作。假设驱动程序、主机、端口、用户名和密码相同
'testDB' => [
'driver' => 'mysql',
'host' => 'localhost',
'port' => '1234',
'database' => 'testDB',
'username' => 'root',
'password' => '',
],
这应该行得通
Route::get('test', function(){
DB::statement('CREATE DATABASE testDB;'); //create database
config(['database.testDB' => [
'driver' => 'mysql',
'host' => 'localhost',
'port' => '1234',
'database' => 'testDB',
'username' => 'root',
'password' => '',
]]);
DB::connection('testDB')->table('some_tables'); //would like to connect this newly created database but config/database.php havent setup yet
});
但是,请注意,这种情况不会持续-它不会更新配置文件。后续的页面视图将不会有新的连接。嗯…它不会更新database.php文件…它保持不变…顺便说一句,您有一些输入错误,应该关闭
]]代码>对,很抱歉,修正了输入错误。很好的一点@ceejayoz,这实际上并没有写入database.php,它只是在整个过程中设置了一个新的配置选项。你能澄清一下吗?新的数据库连接是否应该永久保存在config/database.php
中?是的,我想永久保存它新数据库创建的频率是多少?你预计会有多少人被关闭?取决于管理员…可能是10个数据库/月…或者更多,你可能想考虑其他方法,比如多租户数据库结构。
Route::get('test', function(){
DB::statement('CREATE DATABASE testDB;'); //create database
config(['database.testDB' => [
'driver' => 'mysql',
'host' => 'localhost',
'port' => '1234',
'database' => 'testDB',
'username' => 'root',
'password' => '',
]]);
DB::connection('testDB')->table('some_tables'); //would like to connect this newly created database but config/database.php havent setup yet
});