1

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'  => '',
    ],
6
  • Can you clarify - should the new database connection be permanently saved in config/database.php? Commented Jan 30, 2019 at 14:15
  • yes, i would like to permanently save it Commented Jan 30, 2019 at 14:17
  • How often are new databases created? How many do you anticipate winding up with? Commented Jan 30, 2019 at 14:18
  • depends on the admin...maybe 10 database/month...or maybe more Commented Jan 30, 2019 at 14:19
  • You may want to consider other approaches, like a multi-tenant database structure. Commented Jan 30, 2019 at 14:22

1 Answer 1

2

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
});
Sign up to request clarification or add additional context in comments.

3 Comments

Note, however, that this won't persist - it doesn't update the config file. Subsequent pageviews won't have the new connection.
hmm...it does not update the database.php file...it stay the same...btw, you have some typo there should be closing ]]);
Right, sorry about that, fixed the typo. Good point @ceejayoz, this doesn't actually write to database.php, it just sets a new config option for the duration of the process.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.