Back

Changing Eloquent models database connection at runtime


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 a loop at runtime :

foreach ($array as $key => $value) {

   Config::set('database.connections.mysql.database', $key . '_' . $database);
   
   $productRepo = new ProductRepository();
   
   $products = $productRepo->all();

}

Inside the product repository, i'm calling the Eloquent methods all() to get all the products in the database.

What i discover was that the connection was changed to the first value in the array but it does not change on further executions of the loop.

Is there anything I can do to force Eloquent to resolve the connection parameters at runtime?

astroanu replied 3 years ago Solution

See my reply on this thread http://laravel.io/forum/03-02-2015-how-to-change-default-database-connection-in-controller?page=1#reply-21873

parn09 replied 3 years ago

thanks for the solution @astroanu I was still hoping for someone to explain how the model connection gets resolved at runtime though.

dudalubos replied 1 year ago

Hi. You can simply extend the used base Model class with a new one, and have the following inside it:

/**
* @return string
*/
public function getConnectionName()
{
    $databaseConnection = config($this->getConfigFileName().'.database_connection');
    if (!empty($databaseConnection)) {
       $this->connection = $databaseConnection;
    }
    return parent::getConnectionName();        
 }

Then you simply produce a function called 'getConfigFileName()'. This way you specify connection name for any implementations of this new Model extension class dynamically using config file(s).

Hope this helps.


Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us