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

3
  • What have you tried so far? Commented Jul 21, 2018 at 4: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 Commented Jul 21, 2018 at 5:05
  • 3
    check this may help you stackoverflow.com/questions/42198046/… Commented Jul 21, 2018 at 5:06

1 Answer 1

1

use config() helper from laravel.

to set new config for default database connection, do:

config()->set('database.default', 'mysql2');
Sign up to request clarification or add additional context in comments.

3 Comments

i have tried this one but not working or maybe this solution is only applicable to a single request not for all the request
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.
thanks a lot man(Pusparaj), i really owe you, your suggestion worked like a magic for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.