> This page location: /docs.md > /docs/drivers.md > /docs/languages/php.md > /docs/drivers/php/laravel-mongodb/current.md

> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

# Get Started with Laravel MongoDB

## 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](https://www.mongodb.com/docs/php-library/current/connect/) 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](https://github.com/mongodb-university/laravel-quickstart/) GitHub repository.

## Prerequisites

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

- [PHP](https://www.php.net/downloads)

- [Composer](https://getcomposer.org/doc/00-intro.md)

- 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](https://herd.laravel.com/docs/1/herd-pro-services/mongodb) in the Herd documentation.

1. 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](https://www.mongodb.com/docs/php-library/current/get-started/#install-the-mongodb-php-extension) step of the Get Started with the PHP Library guide.

2. 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](https://www.mongodb.com/docs/drivers/compatibility/?driver-language=php\&php-driver-framework=laravel) page.

   Run the following command to install Laravel:

   ```bash
   composer global require laravel/installer
   ```

   When the installation completes, the command outputs the following message:

   ```none
   Using version ^<version number> for laravel/installer
   ```

3. Create a Laravel application

   Run the following command to generate a new Laravel web application called `my-app`:

   ```bash
   laravel new my-app
   ```

   When the installation completes, the command outputs the following message:

   ```none
   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. Add Laravel MongoDB to the dependencies

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

   ```bash
   cd my-app
   ```

   Run the following command to add the Laravel MongoDB dependency to your application:

   ```bash
   composer require mongodb/laravel-mongodb:^5.12
   ```

   When the installation completes, verify that the `composer.json` file includes the following line in the `require` object:

   ```json
   "mongodb/laravel-mongodb": "^5.12"
   ```

   After completing these steps, you have a new Laravel project with the Laravel Integration dependencies installed.

## Create a MongoDB Deployment

1. Create a free MongoDB deployment on Atlas

   Complete the [MongoDB Get Started](https://www.mongodb.com/docs/get-started/?language=php) guide to set up a new Atlas account and load sample data into a new free cluster. Follow the instructions in the Cloud Deployment tabs to create your MongoDB Atlas deployment in the cloud.

2. Save your credentials

   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 cluster 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](https://www.mongodb.com/docs/manual/reference/connection-string/) in the Server manual.

1. Find your MongoDB Atlas connection string.

   To retrieve your connection string for the deployment that you created in the [previous step](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started.md#std-label-laravel-quick-start-create-deployment), 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](/_includes/figures/atlas_connect_to_cluster.png)

   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. Copy your connection string.

   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](/_includes/figures/atlas_copy_connection_string_php.png)

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

1. 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:

   ```sh
   cp .env.example .env
   ```

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

   ```bash
   php artisan key:generate
   ```

   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](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/get-started.md#std-label-laravel-quick-start-connection-string) step:

   ```bash
   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:

   ```bash
   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. 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:

   ```php
   'default' => env('DB_CONNECTION'),
   ```

   Add the following highlighted `mongodb` entry to the `connections` array in the same file:

   ```php
   'connections' => [
     'mongodb' => [
       'driver' => 'mongodb',
       'dsn' => env('DB_URI'),
       'database' => 'sample_mflix',
     ],
   ],

   // ...
   ```

3. Add the Laravel Integration provider

   Open the `providers.php` file in the `bootstrap` directory and add the following entry into the array:

   ```text
   MongoDB\Laravel\MongoDBServiceProvider::class,
   ```

   **Tip:**

   To learn how to register the provider in Laravel 10.x, see [Registering Providers.](https://laravel.com/docs/10.x/providers#registering-providers)

After completing these steps, your Laravel web application is ready to connect to MongoDB.

## View MongoDB Data

1. 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:

   ```bash
   php artisan make:model Movie -cr
   ```

   When the command completes, it outputs the following message:

   ```none
   INFO  Model [app/Models/Movie.php] created successfully.

   INFO  Controller [app/Http/Controllers/MovieController.php]
   created successfully.
   ```

2. 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\Model` import with `MongoDB\Laravel\Eloquent\Model`

   - Specify `"mongodb"` in the `$connection` field

   The edited `Movie.php` file contains the following code:

   ```php
   <?php

   namespace App\Models;

   use MongoDB\Laravel\Eloquent\Model;

   class Movie extends Model
   {
       protected $connection = 'mongodb';
   }
   ```

3. 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:

   ```php
   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. Add a web route

   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
   <?php

   // ...
   use App\Http\Controllers\MovieController;

   Route::get('/browse_movies/', [MovieController::class, 'show']);
   ```

5. Generate a view

   Run the following command from the application root directory to create a view that displays movie data:

   ```bash
   php artisan make:view browse_movies
   ```

   After you run the command, it outputs the following message:

   ```none
   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:

   ```html
   <!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. 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:

   ```php
   public function show()
   {
       $results = Movie::where('runtime', '<', 60)
           ->where('imdb.rating', '>', 8.5)
           ->orderBy('imdb.rating', 'desc')
           ->take(10)
           ->get();

       return $results->toJson();
   }
   ```

7. Start your Laravel application

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

   ```bash
   php artisan serve
   ```

   After the server starts, it outputs the following message:

   ```none
   INFO  Server running on [http://127.0.0.1:8000].

   Press Ctrl+C to stop the server
   ```

8. View the movie data

   Open the URL [http://127.0.0.1:8000/browse\_movies](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

1. Implement the function to insert data

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

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

2. Add an API route that calls the controller function

   Generate an API route file by running the following command:

   ```bash
   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:

   ```php
   use App\Http\Controllers\MovieController;

   // ...

   Route::resource('movies', MovieController::class)->only([
       'store'
   ]);
   ```

3. Update the model fields

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

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

4. Post a request to the API

   Create a file called `movie.json` and insert the following data:

   ```json
   {
     "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:

   ```bash
   curl -H "Content-Type: application/json" \
     --data @movie.json \
     http://localhost:8000/api/movies
   ```

5. View the data

   Open [http://127.0.0.1:8000/browse\_movies](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](https://github.com/mongodb-university/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](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/backend-service-tutorial.md#std-label-laravel-tutorial-backend-service) 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](https://www.youtube.com/watch?v=VK-2j5CNsvM) tutorial on YouTube.

### Further Learning

Learn more about Laravel MongoDB features from the following resources:

- [Connect to MongoDB](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/connect/connect-to-mongodb.md#std-label-laravel-fundamentals-connection): learn how to configure your MongoDB connection.

- [Interact with Data](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/insert.md#std-label-laravel-fundamentals-insert-documents): learn how to read and write your MongoDB data.

- [Model Your Data](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/model-data/model-class.md#std-label-laravel-eloquent-model-class): use Eloquent model classes to work with MongoDB data.

- [Query Builder](https://www.mongodb.com/docs/drivers/php/laravel-mongodb/current/interact-data/query-builder.md#std-label-laravel-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](https://stackoverflow.com/questions/tagged/mongodb) or the MongoDB [Reddit community.](https://www.reddit.com/r/mongodb/)
