Laravel - changing the default connection globally by default

In my database.php , I have two databases installed.

 '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', ), 

Thus, by default, db1 first set as the base database. Now I want to switch the default database to "db2" by selecting an option from the "Select" drop-down list. This will make an AJAX mail 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 am "refreshing" the page, but the connection is still in "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 it works fine, and it successfully switches the database. Is the per-request switch basic?

+7
php laravel
source share
2 answers

Config::set will only work for each request, so you probably want to set up your database in a session and capture it on subsequent requests.

You have options where to do this. /app/start/global would be one option. In the constructor of the controller will be different. You can also register a service provider to do this.

The following is an example of how the code might look like [warning: unverified 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 updating the database configuration function:

 public function postChangeDb() { $db = Input::get('db'); Session::put('selected_database',$db); Config::set('database.default', $db); } 
+5
source share

Have you tried just changing the default connection in app/config/database.php ?

 'default' => 'db2' 

If this is not the case, please provide additional information about the problem.

Edit: Thus, it seems that you have all the connections hardcoded in the models. Try updating these models:

  protected $connection = 'db2'; 
+2
source share

All Articles