skip to Main Content

I want to configure both MySQL and MongoDB connections in my .env file in Laravel. How can I set the following parameters for both:

DB_CONNECTION=
DB_HOST=
DB_PORT=
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=.

2

Answers


  1. You can define new env variables and create a new connection for mongoDB in config/database.php:

    'connections' => [
      // Other connections ...
    
      'mongodb' => [
            'driver' => 'mongodb',
            'dsn' => 'mongodb+srv://' . env('MONGO_USERNAME') . ':' . env('MONGO_PASSWORD') . '@' . env('MONGO_CLUSTER') . '/' . env('MONGO_DATABASE') . '?retryWrites=true&w=majority',
            'database' => env('MONGO_DATABASE'),
    ],
    
    Login or Signup to reply.
  2. in your .env:

    # MySQL Database Configuration
    DB_CONNECTION=mysql
    MYSQL_DB_HOST=127.0.0.1
    MYSQL_DB_PORT=3306
    MYSQL_DB_DATABASE=my_database
    MYSQL_DB_USERNAME=root
    MYSQL_DB_PASSWORD=secret_password
    
    # MongoDB Database Configuration
    MONGO_DB_CONNECTION=mongodb
    MONGO_DB_HOST=127.0.0.1
    MONGO_DB_PORT=27017
    MONGO_DB_DATABASE=my_mongo_database
    MONGO_DB_USERNAME=mongo_user
    MONGO_DB_PASSWORD=mongo_password
    

    in config/database.php:

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('MYSQL_DB_HOST', '127.0.0.1'),
        'port' => env('MYSQL_DB_PORT', '3306'),
        'database' => env('MYSQL_DB_DATABASE', 'forge'),
        'username' => env('MYSQL_DB_USERNAME', 'forge'),
        'password' => env('MYSQL_DB_PASSWORD', ''),
    ],
    
    'mongodb' => [
        'driver'   => 'mongodb',
        'host'     => env('MONGO_DB_HOST', 'localhost'),
        'port'     => env('MONGO_DB_PORT', 27017),
        'database' => env('MONGO_DB_DATABASE'),
        'username' => env('MONGO_DB_USERNAME'),
        'password' => env('MONGO_DB_PASSWORD'),
        'options'  => [
            'database' => 'admin', 
        ]
    ],
    

    don’t forget to run php artisan config:cache after make these changes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search