Is there any way to force Eloquent models to re resolve the connection they were instantiated with?
Right now I have a method that changes the database connection in
Each database is really a separate connection, so I would setup all the connections to the database in the config/database.php
file, and then you can use the setConnection()
method on the model to switch between them.
database.php:
return [
'default' => 'mysql-key1',
'connections' => [
'mysql-key1' => [
'driver' => 'mysql',
'database' => 'key1_dbname,
// etc
],
'mysql-key2' => [
'driver' => 'mysql',
'database' => 'key2_dbname',
// etc
]
]
];
ProductRepository.php:
public function setConnection($name) {
// assumes $this->product is your Product model
$this->product->setConnection($name);
}
Code:
$productRepo = new ProductRepository();
foreach ($array as $key => $value) {
$productRepo->setConnection($key . '_' . $database);
$products = $productRepo->all();
}
additional information based on comments
Laravel is only going to instantiate a connection to the database the first time it is needed. Once the connection has been created, it is going to reuse it. It would be a huge performance issue if you had to reconnect to the database for every single query.
That being said, if you really want to do this the way you originally designed it, all you would need to do is call the DB::reconnect()
method after updating the config.
foreach ($array as $key => $value) {
Config::set('database.connections.mysql.database', $key . '_' . $database);
DB::reconnect();
$productRepo = new ProductRepository();
$products = $productRepo->all();
}
However, I would strongly urge you to consider the originally described option so that you're not making a ton of unnecessary connections.
In my case, I did not have a database config for each of my databases, since they are created dynamically. I used the following approach, just changing the table name to include the database name as well (This works for MySQL):
foreach ($array as $key => $value) {
$productRepo = new ProductRepository();
$productRepo->setTable($key . '_' . $database);
$products = $productRepo->all();
}