Mister Verleg
Mister Verleg

Reputation: 4293

Laravel load database

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?

Upvotes: 2

Views: 1052

Answers (1)

Brian Lee
Brian Lee

Reputation: 18187

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()
    ...
]

Upvotes: 1

Related Questions