Reputation: 41
I'm working on a CMS with Laravel to manage other databases. Now i use the config function to create a temporary config variable. I do this for the external database and it also works.
This is what my code looks like now:
$website = Website::where('hash', '=', $hash)->first();
config(['database.connections.extern.host' => $website->db_host]);
config(['database.connections.extern.database' => $website->db_name]);
config(['database.connections.extern.username' => $website->db_username]);
config(['database.connections.extern.password' => $website->db_password]);
The problem is now, wherever I want to call the external database, I should do this. That is of course not convenient.
Does anyone know a solution to this 'problem'?
Upvotes: 2
Views: 686
Reputation: 950
You can loop through Website model and set config file at the startup and use website's hash as the key:
foreach (Website::all() as $website) {
config(['database.connections.'.$website->hash.'.host' => $website->db_host]);
...
}
And then use website hash to connect to relevant DB:
DB::connection($hash) ...
Anyway this is not a good way to manage other databases if they are on different hosts. You better use web services technique to do such work. Connecting to external DB is potentially insecure.
Upvotes: 1