3

I'm using Laravel 5.6 and I would like to set the default database based on the authenticated user

like when user1 logged the DB1 set as default and like so with user2 set the databse to DB2

any suggest or other ways to make it?

thanks

PsyLogic
  • 639
  • 4
  • 10
  • Possibly related: https://stackoverflow.com/questions/18975500/laravel-change-the-default-database-connection-globally – waterloomatt May 04 '18 at 14:54
  • See how you can handle multiple databases here: https://stackoverflow.com/questions/31847054/how-to-use-multiple-database-in-laravel – Hemerson Varela May 04 '18 at 14:55

2 Answers2

2

First you can update the connection configuration details with the relevant values based on your user (I'm assuming here that the default connection name is mysql):

// This will overwrite only the values you need updated so you don't have
// to add all of the configuration keys like 'driver', 'charset', etc
config()->set('database.connections.mysql', array_merge(config('database.connections.mysql'), [
    'database' => 'new_database',
    'username' => 'new_username',
    'password' => 'new_password',
]));

Then you just need to reconnect to the database and it will use the new configuration:

\DB::reconnect('mysql');

All this code would probably be best placed in a middleware, so it runs automatically on each request.

Bogdan
  • 43,166
  • 12
  • 128
  • 129
1

using Illuminate\Support\Facades\Auth;

you could do

 if(Auth::user()->type == 1){
      $users = DB::connection('DB1 ')->select(...);
 }else{
      $users = DB::connection('user2 ')->select(...);
 }