For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

Get Started with Laravel MongoDB

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.

To create the Get Started application, you need the following software installed in your development environment:

  • PHP

  • A terminal app and shell. For MacOS users, use Terminal or a similar app. For Windows users, use PowerShell.

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.

1

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.

2

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
3

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!
4

Navigate to the application directory you created in the previous step:

cd my-app

Run the following command to add the Laravel application encryption key, which is required to encrypt cookies:

php artisan key:generate
5

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.

1

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.

2

After you create your database user, save that user's username and password to a safe location for use in an upcoming step.

After completing these steps, you have a new free tier MongoDB deployment on Atlas, database user credentials, and sample data loaded into your database.

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.

1

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.

The connect button in the clusters section of the
Atlas UI

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.

2

Click the copy icon on the right of the connection string to copy it to your clipboard as shown in the following screenshot:

The connection string copy button in the Atlas UI
3

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.

1

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.

2

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',
],
],
// ...
3

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.

1

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.
2

Open the Movie.php model in your app/Models directory and make the following edits:

  • Replace the Illuminate\Database\Eloquent\Model import with MongoDB\Laravel\Eloquent\Model

  • Specify "mongodb" in the $connection field

The edited Movie.php file contains the following code:

<?php
namespace App\Models;
use MongoDB\Laravel\Eloquent\Model;
class Movie extends Model
{
protected $connection = 'mongodb';
}
3

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()
]);
}
4

Open the web.php file in the routes directory. Add an import for the MovieController and a route called browse_movies as shown in the following code:

<?php
// ...
use App\Http\Controllers\MovieController;
Route::get('/browse_movies/', [MovieController::class, 'show']);
5

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>
6

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();
}
7

Run the following command from the application root directory to start your PHP built-in web server:

php artisan serve

After the server starts, it outputs the following message:

INFO Server running on [http://127.0.0.1:8000].
Press Ctrl+C to stop the server
8

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.

1

Replace the store() method in the MovieController.php file, located in the app/Http/Controllers directory with the following code:

public function store(Request $request)
{
$data = $request->all();
$movie = new Movie();
$movie->fill($data);
$movie->save();
}
2

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'
]);
3

Update the Movie model in the app/Models directory to specify the fields that the fill() method populates as shown in the following code:

class Movie extends Model
{
protected $connection = 'mongodb';
protected $fillable = ['title', 'year', 'runtime',
'imdb', 'plot'];
}
4

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
5

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.

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.

Learn more about Laravel MongoDB features from the following resources:

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.