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…
use illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;Set the configurationConfig::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
You may experience issues if you have a cached config. In this case Laravel is retrieving your applications config from the cache and not directly because to improve performance, the configuration is usually bundled into a single file.
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….
Feedbacks and insights would be highly appreciated.