简体   繁体   中英

Laravel, how to append new connection in config/database.php file?

My goal is to append/generate new connection in config/database.php file right after I created new database trough DB::statement

There is a similar question here , but the problem is that it is pre-defined in config/database.php.

web.php (route)

Route::get('test', function(){

    DB::statement('CREATE DATABASE testDB;'); //create database

    //append/generate new connection in config/database.php logic here

    DB::connection('testDB')->table('some_tables'); //would like to connect this newly created database but config/database.php havent setup yet
});

config/database.php

Would like to see it is edited on the fly like this below. But I don't have any idea how to do it without manually editing the actual file. Assume the driver, host, port, username and password are the same.

'testDB' => [
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'port'      => '1234',
        'database'  => 'testDB',
        'username'  => 'root',
        'password'  => '',
    ],

This should work

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM