In laravel 5, I created Middleware that changes the database credentials:
config([
'database.connections.mysql.database' => 'someDB',
'database.connections.mysql.username' => 'someUser',
'database.connections.mysql.password' => 'somePass'
]);
Using a route that makes use of the middleware, I tried to output the current database within the controller:
exit(config('database.connections.mysql.database'));
The information is correctly set to 'someDB'
. When I use eloquent in the same function it tries to contact the 'old' database and not the 'someDB'
settings I've set in the middleware.
Any thoughts about this?
I found a solution by just creating a new connection:
config([
'database.connections.mysql2.database' => 'someDB',
'database.connections.mysql2.username' => 'someUser',
'database.connections.mysql2.password' => 'somePass',
'database.connections.mysql2.driver' => 'mysql',
'database.connections.mysql2.host' => 'localhost',
.....
// setting default connection to mysql2
'database.default' => 'mysql2',
]);