2

I am working in a Laravel application where there is a database that changes over time,

it might be called

 20042018 

today and

  21042018 

tomorrow I know how to calculate its name, I just don't know where to add the script to find the db name.

Must I do this in a modal? or is there a constructor somewhere where I am supposed to set a dynamic DB?

In my database.php file, I want to include this DB., but how can I dynamically add this database to my driver in database.php?

1 Answer 1

1

Could set in your AppServiceProvider.php register function:

public function register()
{
     $db = 2104018; // calculate the name

     config(['database.connections.mysql' => [
        'driver'    => 'mysql',
        'host'      => config('database.connections.mysql.host'),
        'database'  => $db,
        'username'  => config('database.connections.mysql.username'),
        'password'  => config('database.connections.mysql.password'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ]]);
}

Or another way would be to create a helper function in app/helpers.php, add it to your composer.json under "autoload": { "files": ["app/helpers.php"] } and call it from the database.php config file:

// app/helpers.php
if (!function_exists('calculate_db_name')) {
    function calculate_db_name() {
        $db = 12345; // do the thing...
        return $db;
    }
}

// config/database.php
'mysql' => [
    ...
    'database' => calculate_db_name()
    ...
]
Sign up to request clarification or add additional context in comments.

4 Comments

This is a nice and elegant solution!
Agreed, it's a pretty common approach for multi tenant apps that needs to switch the database connection based on an active user id, although it's usually done in middleware.
Quick question, what is the impact of using env() in the code base instead of accessing by config() especially when caching your config files for production usage?
Bad things can happen. Calls to env() not within config files will return null after php artisan cache:config is ran. All config files are compiled into one for quick loading. Full disclosure, I copy pasted this from the config/database.php file without thinking twice of it, I will update the answer accordingly. Thanks for pointing that out.

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.