Configure Your MongoDB Connection
Configure the application environment variable file
Copy the .env.example
file to a file named .env
in the project
root directory by running the following shell command:
cp .env.example .env
Open the .env
file and add or edit the following variables and values.
Replace the <connection string>
placeholder with your connection
string from the Create a Connection String step:
DB_CONNECTION=mongodb DB_URI="<connection string>"
For example, if your connection string is
"mongodb+srv://myUser:myPass123@mongo0.example.com/"
,
your DB_URI
variable matches the following line:
DB_URI="mongodb+srv://myUser:myPass123@mongo0.example.com/"
Note
Make sure these variables in your .env
file are undefined in the
shell in which you run your application. Environment variables in
the shell take precedence over the ones in the .env
file.
Set the connection string in the database configuration
Open the database.php
file in the config
directory and set the
default database connection to the DB_CONNECTION
environment
variable as shown in the following line:
'default' => env('DB_CONNECTION'),
Add the following highlighted mongodb
entry to the connections
array
in the same file:
'connections' => [ 'mongodb' => [ 'driver' => 'mongodb', 'dsn' => env('DB_URI'), 'database' => 'sample_mflix', ], // ...
Add the Laravel MongoDB provider
Open the providers.php
file in the bootstrap
directory and add
the following entry into the array:
MongoDB\Laravel\MongoDBServiceProvider::class,
Tip
To learn how to register the provider in Laravel 10.x, see Registering Providers.
After completing these steps, your Laravel web application is ready to connect to MongoDB.
Note
If you run into issues, ask for help in the MongoDB Community Forums or submit feedback by using the Rate this page tab on the right or bottom right side of the page.