Overview
This guide shows you how to add Laravel MongoDB to a new Laravel web application, connect to a MongoDB cluster hosted on MongoDB Atlas, and perform read and write operations on the data.
Tip
If you prefer to connect to MongoDB by using the MongoDB PHP Library without Laravel, see Connect to MongoDB in the MongoDB PHP Library documentation.
The Laravel Integration extends the Laravel Eloquent and Query Builder syntax to store and retrieve data from MongoDB.
MongoDB Atlas is a fully managed cloud database service that hosts your MongoDB deployments. You can create your own free (no credit card required) MongoDB Atlas deployment by following the steps in this guide.
Tip
You can download the complete web application project by cloning the laravel-quickstart GitHub repository.
Prerequisites
To create the Get Started application, you need the following software installed in your development environment:
A terminal app and shell. For MacOS users, use Terminal or a similar app. For Windows users, use PowerShell.
Download and Install
Complete the following steps to install and add the Laravel Integration dependencies to a Laravel web application.
Tip
As an alternative to the following installation steps, you can use Laravel Herd to install MongoDB and configure a development environment for Laravel MongoDB. For more information about using Laravel Herd with MongoDB, see Installing MongoDB via Herd Pro in the Herd documentation.
Install the MongoDB PHP Extension
Laravel MongoDB requires the MongoDB PHP Extension to manage MongoDB connections and commands. To learn how to install the MongoDB PHP Extension, see the Install the MongoDB PHP extension step of the Get Started with the PHP Library guide.
Install Laravel
Ensure that the version of Laravel you install is compatible with the version of the Laravel Integration. To learn which versions are compatible, see the Compatibility page.
Run the following command to install Laravel:
composer global require laravel/installer
When the installation completes, the command outputs the following message:
Using version ^<version number> for laravel/installer
Create a Laravel application
Run the following command to generate a new Laravel web application called my-app:
laravel new my-app
When the installation completes, the command outputs the following message:
INFO Application ready in [my-app]. You can start your local development using: ➜ cd my-app ➜ php artisan serve New to Laravel? Check out our bootcamp and documentation. Build something amazing!
Add Laravel MongoDB to the dependencies
Run the following command to add the Laravel MongoDB dependency to your application:
composer require mongodb/laravel-mongodb:^5.8
When the installation completes, verify that the composer.json file includes the following line in the require object:
"mongodb/laravel-mongodb": "^5.8"
After completing these steps, you have a new Laravel project with the Laravel Integration dependencies installed.
Create a MongoDB Deployment
Create a free MongoDB deployment on Atlas
Complete the MongoDB Get Started guide to set up a new Atlas account and load sample data into a new free tier MongoDB deployment. Follow the instructions in the Cloud Deployment tabs to create your MongoDB Atlas deployment in the cloud.
After completing these steps, you have a new free tier MongoDB deployment on Atlas, database user credentials, and sample data loaded into your database.
Create a Connection String
You can connect to your MongoDB deployment by providing a connection URI, also called a connection string, which instructs the driver on how to connect to a MongoDB deployment and how to behave while connected.
The connection string includes the hostname or IP address and port of your deployment, the authentication mechanism, user credentials when applicable, and connection options.
To connect to an instance or deployment not hosted on Atlas, see Connection Strings in the Server manual.
Find your MongoDB Atlas connection string.
To retrieve your connection string for the deployment that you created in the previous step, log in to your Atlas account and navigate to the Clusters page under the Database section. Click the Connect button for your new deployment.

If you do not already have a database user configured, MongoDB will prompt you to create and configure a new user.
Click the Drivers button under Connect to your application and select "PHP" from the Driver selection menu and the version that best matches the version you installed from the Version selection menu.
Ensure the View full code sample option is deselected to view only the connection string.
Update the password placeholder.
Paste this connection string into a file in your preferred text editor and replace the <db_password> placeholder with your database user's password. The connection string is already populated with your database user's username.
Save this file to a safe location for use in the next step.
After completing these steps, you have a connection string that contains your database username and password.
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 Integration 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.
View MongoDB Data
Create a model and controller
Create a model called Movie to represent data from the sample movies collection in your MongoDB database and the corresponding resource controller by running the following command:
php artisan make:model Movie -cr
When the command completes, it outputs the following message:
INFO Model [app/Models/Movie.php] created successfully. INFO Controller [app/Http/Controllers/MovieController.php] created successfully.
Edit the model to use the Laravel Integration
Open the Movie.php model in your app/Models directory and make the following edits:
Replace the
Illuminate\Database\Eloquent\Modelimport withMongoDB\Laravel\Eloquent\ModelSpecify
"mongodb"in the$connectionfield
The edited Movie.php file contains the following code:
namespace App\Models; use MongoDB\Laravel\Eloquent\Model; class Movie extends Model { protected $connection = 'mongodb'; }
Add a controller function
Open the MovieController.php file in your app/Http/Controllers directory. Replace the show() function with the following code to retrieve results that match a database query and render it in the view:
public function show() { return view('browse_movies', [ 'movies' => Movie::where('runtime', '<', 60) ->where('imdb.rating', '>', 8.5) ->orderBy('imdb.rating', 'desc') ->take(10) ->get() ]); }
Generate a view
Run the following command from the application root directory to create a view that displays movie data:
php artisan make:view browse_movies
After you run the command, it outputs the following message:
INFO View [resources/views/browse_movies.blade.php] created successfully.
Open the browse_movies.blade.php view file in the resources/views directory. Replace the contents with the following code and save the changes:
<!DOCTYPE html> <html> <head> <title>Browse Movies</title> </head> <body> <h2>Movies</h2> @forelse ($movies as $movie) <p> Title: {{ $movie->title }}<br> Year: {{ $movie->year }}<br> Runtime: {{ $movie->runtime }}<br> IMDB Rating: {{ $movie->imdb['rating'] }}<br> IMDB Votes: {{ $movie->imdb['votes'] }}<br> Plot: {{ $movie->plot }}<br> </p> @empty <p>No results</p> @endforelse </body> </html>
Optionally, view your results as JSON documents
Rather than generating a view and editing the browse_movies.blade.php file, you can use the toJson() method to display your results in JSON format.
Replace the show() function with the following code to retrieve results and return them as JSON documents:
public function show() { $results = Movie::where('runtime', '<', 60) ->where('imdb.rating', '>', 8.5) ->orderBy('imdb.rating', 'desc') ->take(10) ->get(); return $results->toJson(); }
View the movie data
Open the URL http://127.0.0.1:8000/browse_movies in your web browser. The page shows a list of movies and details about each of them.
Tip
You can run the php artisan route:list command from your application root directory to view a list of available routes.
Write Data to MongoDB
Add an API route that calls the controller function
Generate an API route file by running the following command:
php artisan install:api
Tip
Skip this step if you are using Laravel 10.x because the file that the command generates already exists.
Import the controller and add an API route that calls the store() method in the routes/api.php file:
use App\Http\Controllers\MovieController; // ... Route::resource('movies', MovieController::class)->only([ 'store' ]);
Post a request to the API
Create a file called movie.json and insert the following data:
{ "title": "The Laravel MongoDB Quick Start", "year": 2024, "runtime": 15, "imdb": { "rating": 9.5, "votes": 1 }, "plot": "This movie entry was created by running through the Laravel MongoDB Quick Start tutorial." }
Send the JSON payload to the endpoint as a POST request by running the following command in your shell:
curl -H "Content-Type: application/json" \ --data @movie.json \ http://localhost:8000/api/movies
View the data
Open http://127.0.0.1:8000/browse_movies in your web browser to view the movie information that you submitted. The inserted movie appears at the top of the results.
Next Steps
Congratulations on completing the Get Started guide!
After you complete these steps, you have a Laravel web application that uses Laravel MongoDB to connect to your MongoDB deployment, run a query on the sample data, and render a retrieved result.
You can download the web application project by cloning the laravel-quickstart GitHub repository.
Tip
Tutorials
Learn how to implement more CRUD functionality in a Laravel MongoDB application by following the Build a Back End Service by Using Laravel MongoDB tutorial.
Learn how to build a full stack application that uses Laravel MongoDB by following along with the Full Stack Instagram Clone with Laravel and MongoDB tutorial on YouTube.
Further Learning
Learn more about Laravel MongoDB features from the following resources:
Connect to MongoDB: learn how to configure your MongoDB connection.
Interact with Data: learn how to read and write your MongoDB data.
Model Your Data: use Eloquent model classes to work with MongoDB data.
Query Builder: use the query builder to specify MongoDB queries and aggregations.
Note
If you run into issues on this page, submit feedback by using the Rate this page tab on the right or bottom right side of this page.
You can find support for general questions by using the MongoDB Stack Overflow tag or the MongoDB Reddit community.
