skip to Main Content

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


  1. 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:

    $dbName = DB::connection('mongodb')->getDatabaseName();
    //or
    $dbName = DB::connection()->getDatabaseName();
    

    I guess you can/should log in as a vendor and check that you are connected to the correct database

    Login or Signup to reply.
  2. 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.

    // Retrieve the current database name from the Laravel configuration
    $currentDatabaseName = config('database.connections.mongodb.database');
    
    // Get the MongoDB client from the connection
    $mongoClient = DB::connection('mongodb')->getMongoClient();
    
    // Use the getDatabase method to get the current database object
    $currentDatabase = $mongoClient->selectDatabase($currentDatabaseName);
    
    // Now, you can use $currentDatabase to perform operations on the current database
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search