Laravel - change the default database connection globally

后端 未结 2 417
再見小時候
再見小時候 2020-12-29 13:29

In my database.php, I have TWO databases configured.

\'db1\' => array(
  \'driver\'   => \'pgsql\',
  \'host\'     => \'localhost\',
           


        
相关标签:
2条回答
  • 2020-12-29 13:40

    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);
    }
    
    0 讨论(0)
  • 2020-12-29 14:02

    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';
    
    0 讨论(0)
提交回复
热议问题