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
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
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.
using Illuminate\Support\Facades\Auth;
you could do
if(Auth::user()->type == 1){
$users = DB::connection('DB1 ')->select(...);
}else{
$users = DB::connection('user2 ')->select(...);
}