In my database.php
, I have TWO databases configured.
'db1' => array(
'driver' => 'pgsql',
'host' => 'localhost',
'database' => 'db1',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
),
'db2' => array(
'driver' => 'pgsql',
'host' => 'localhost',
'database' => 'db2',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
),
So by default db1
is set as default DB initially. Now I want to switch the default database to 'db2' by selecting an option from 'select' dropdown. This will do a post AJAX request to the controller method in which I do
public function postChangeDb() {
$db = Input::get('db');
Config::set('database.default', $db);
}
Once this is done, I 'refresh' the page, but the connection is still at 'db1'.
I also tried the following
public function getTest() {
Config::set('database.default', 'db1');
$users = User::all();
echo sizeof($users); // returns 20
Config::set(database.default', 'db2');
$users = User::all();
echo sizeof($users); // returns 50 - which is correct!
}
And the above works fine and it successfully switches the database. Is the switch 'per request' basis?
Config::set
is only going to work on a per-request basis, so you're probably going to want to set your database in the Session and grab it on subsequent requests.
You have some options on where to do that. /app/start/global
would be one option. In the controller constructor would be another. You could register a service provider to do it, too.
Below is an example of what the code might look like [warning: untested code!] in the controller constructor:
public function __construct() {
if(Session::has('selected_database'){
Config::set('database.default',Session::get('selected_database'));
} else {
return Redirect::to('database_choosing_page');
}
}
and an update to your database setting function:
public function postChangeDb() {
$db = Input::get('db');
Session::put('selected_database',$db);
Config::set('database.default', $db);
}
Have you tried simply to change the default connection in app/config/database.php
?
'default' => 'db2'
If it's not the case then please provide more information on the problem.
Edit: So it seems you have all connections hardcoded in the models. Try updating the models like that:
protected $connection = 'db2';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With