Connect laravel jenssegers to mongodb atlas cluster
In Laravel, Use 'dsn' key in config/database.php as shown below to mention the complete cluster url.
'mongodb_conn' => [ 'driver' => 'mongodb', 'dsn'=>'mongodb://username:password@host1,host2/database?ssl=true&replicaSet=replicaSet&authSource=admin', 'database' => 'my_data', ]
Following works for me, MongoDB Atlas and Laravel 5.7:
update config/database.php
:
'mongodb' => [ 'driver' => 'mongodb', 'dsn' => 'mongodb+srv://<username>:<password>@cluster0.kxxi7.mongodb.net/mydatabase?retryWrites=true&w=majority', 'database' => 'mydatabase', ],
Set your connection string at dsn
and db name at database
.
By default, when assembling the connection string, the Jenssegers\Mongodb package assembles a DSN that starts with mongodb://. In order to connect to a mongoDB atlas instance, the DSN needs to start with mongodb+srv://.
The simplest and most flexible way to handle this is to add the following entry to your .env:
MONGO_DB_BASE_URI=mongodb+srv://
Then, in your database.php, your mongodb entry should look like the following:
'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' => [], 'dsn' => env('MONGO_DB_BASE_URI','mongodb://').env('MONGO_DB_HOST', 'localhost') ],
This gives you control over whether you're connecting to a local instance - in which case you can use a DSN of mongodb://, or a cloud instance such as Atlas - in which case you use a DSN of mongodb+srv://.