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:
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.
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:You can specify that
another_connection
variable at yourdatabase.php
file. Like this: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 timeBut 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
but don't forget to purge before to delete the cache
We have a similar scenario, where to look for historic data, we change the database. We use the following in the model:
and then, on the code, we send the $db as a parameter:
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.