How to Set Database Configuration Dynamically in your Laravel Application.

Sometimes we may find ourselves in situations where we have to modify our database connection/configuration at runtime.

Some applications require alot of database and sometimes the required database can only be determined at runtime.

A typical example from my experience was in School Management System that required a separate Database for each school.

Let’s Code…

My approach to this is as follows with some stackoverflow guide.

use illuminate\Support\Facades\Config;

use Illuminate\Support\Facades\DB;

Set the configuration

Config::set(“database.connections.mysql”, [

“driver” => “mysql",

“host” => “localhost”,

“port" => “3306",

“database”=> “db",

“username” => “root",

password” => “root",

]);

This will replace the mysql connection array with the above value. Do this only if you know what you are doing.

A better approach is to modify only the configuration array key of interest, in this case the database name of your mysql connection.

Config::set(“database.connections.mysql.database”, “db_name”);

You can “dd" the configuration to verify during development.

$my_config = Config::get(“database.connections.mysql”);

DB::purge(“mysql");

dd($my_config);

Note that the above method applies to any configuration within the config directory at all and not just the database configuration.

database.connections.mysql is can be traced as follows.

config directory there is a database.php file, within the file there is an associative array called connections, which has an index mysql.

so to access the guards configuration within the auth.php file we use

auth.guards

The Catch is The Cache

Solution: run the artisan command below to clear the cache.

php artisan config:clear

I hope I was able to provide a concise and reasonable solution.

Stay in the light….

A writer and teacher with love for creativity in music and programming

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store