I need to change laravel 5 database connection in run time.
Do you have any idea about it?
Please share with me.
Thanks.
I need to change laravel 5 database connection in run time.
Do you have any idea about it?
Please share with me.
Thanks.
Update: This answer is from 2015! I haven't used Laravel in years and I am not up to date with the latest best practices. This answer keeps getting upvoted so I suppose it works but please proceed with caution.
Well, my immediate answer to this is: don't. Chances are that you can accomplish your task by changing your data model and working with some more advanced relationships. It's hard to tell without knowing what you want to do but it seems to me like a bad idea in general, specially if you're planning on using eloquent models and so on
That said, in some scenario where you really need to alter data in another database or execute some raw query you can use the DB::connection()
method. Something like:
$data = DB::connection('another_connection')->select(...);
You can specify that another_connection
variable at your database.php
file. Like this:
<?php
return array(
'default' => 'mysql',
'connections' => array(
# Your regular connection
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'user',
'password' => 'password'
'charset' => 'utf8',
),
# Your new connection
'another_connection' => array(
'driver' => 'mysql',
'host' => 'another_host',
'database' => 'another_db',
'username' => 'user1',
'password' => 'password1'
'charset' => 'utf8',
),
),
);
You can even specify a connection for each eloquent model using protected $connection = 'another_connection';
also you can specify a connection for each model instance created/queried at run time
$user = new User;
$user->setConnection('another_connection');
$user1 = $user->find(1);
But then again, I personally don't think this is a good idea and it seems to me that everything can get messy and fall apart very quickly as your application grows in complexity.
You can change the connection details during run time using
Config::set('database.connections.mysql.database', 'other_database');
but don't forget to purge before to delete the cache
DB::purge('mysql');
We have a similar scenario, where to look for historic data, we change the database. We use the following in the model:
public function inventory($db, $id) {
return DB::table($db . '.inventory')->where('inventoryid', $id)->get();
}
and then, on the code, we send the $db as a parameter:
$inventory = Inventory::inventory('data_2016', 2);
This way, you don't need to define the connection for each of the different databases and don't tinker with the database config files.
The only downside is that you are unable to use the model directly, instead you have to use the DB helper.