I am using this library (the older version compatible with Laravel 9).
This is my connection string.
'mongodb' => [
'driver' => 'mongodb',
'host' => env('MONGODB_HOST', 'localhost'),
'port' => env('MONGODB_PORT', 27017),
'database' => env('MONGODB_DATABASE'),
'username' => env('MONGODB_USERNAME'),
'password' => env('MONGODB_PASSWORD'),
'options' => [
'database' => env('MONGODB_DATABASE')
]
],
The idea is, when a new vendor would register, a new database would be created. Now when I want to switch between DB’s I am doing this:-
DB::disconnect('mongodb'); // Connection name
DB::purge('mongodb');
Config::set('database.connections.mongodb.database', $databaseName);
Config::set('database.connections.mongodb.options.database', $databaseName);
DB::reconnect('mongodb');
This one gives me the list of all DBs.
$data = DB::connection('mongodb')->getMongoClient()->listDatabases();
print_r($data);
How can I get the DB of the current connection?
2
Answers
on the connection class i see a public method
getDatabaseName()
, so if your database creation is set up correctly you should see the database name with:I guess you can/should log in as a vendor and check that you are connected to the correct database
Here’s how you can do it:
Retrieve the current database name from the Laravel configuration.
Use the getDatabase method on the MongoDB client to get the database object.