Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - change the default database connection globally

Tags:

php

laravel

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?

like image 737
ericbae Avatar asked Sep 24 '13 07:09

ericbae


2 Answers

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);
}
like image 121
J.T. Grimes Avatar answered Oct 29 '22 17:10

J.T. Grimes


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';
like image 23
Sergey Telshevsky Avatar answered Oct 29 '22 19:10

Sergey Telshevsky