2

I want to change the default database in laravel on change of a session key lets say, by default the session key is 'ff' => '20' and the default db is 'default' => env('DB_CONNECTION', 'mysql') and now when I change the value of session key from 'ff' => '20' to 'ff' => '21' I want to change the default db to 'default' => env('DB_CONNECTION', 'mysql2') for all the subsequent request till I don't change the session key again.

I am using laravel 5.5

Krishna Singh
  • 33
  • 1
  • 6
  • What have you tried so far? – Max von Hippel Jul 21 '18 at 04:59
  • tried to make a new global middleware and and changing default db there by DB::setDefaultConnection('DB_CONNECTION','mysql2'); and icluding middleware in controllers construct(), but not working – Krishna Singh Jul 21 '18 at 05:05
  • 3
    check this may help you https://stackoverflow.com/questions/42198046/laravel-change-connection-dynamically – rkj Jul 21 '18 at 05:06

1 Answers1

1

use config() helper from laravel.

to set new config for default database connection, do:

config()->set('database.default', 'mysql2');
Pusparaj
  • 1,469
  • 1
  • 12
  • 19
  • i have tried this one but not working or maybe this solution is only applicable to a single request not for all the request – Krishna Singh Jul 23 '18 at 19:14
  • The above mentioned statement works for a single request if you place this inside your controller, but using this in your middleware helps you to execute the same in all requests that follow through the mentioned middleware. Or if you want to do the same only for a single module (controller), place this in your controller's constructor method. – Pusparaj Jul 25 '18 at 09:30
  • thanks a lot man(Pusparaj), i really owe you, your suggestion worked like a magic for me. – Krishna Singh Aug 10 '18 at 05:59