LAUNCHMongoDB 8.3 is built for the sub-100ms retrieval & zero downtime AI demands. Read blog >
AI DATAStop fighting your data layer. Get the memory & retrieval agents need to scale. Read blog >

MongoDB and Laravel Integration

Connect MongoDB to Laravel in minutes with Atlas.
Get started free

Overview

Laravel is a popular web development framework for PHP. It offers many defaults and provides a code structure that is easy to understand and quick to use for implementing web applications and APIs. MongoDB has an official Laravel integration, available here on github. More information can be found in the official documentation.

In this tutorial, we will look at how you can use Laravel and MongoDB to build web applications and APIs.

Table of Contents

Can I Use MongoDB With Laravel?

Yes! In fact, MongoDB is a great choice for Laravel projects. As we get started with Laravel development using MongoDB, we'll work through an example of how to build a blog application.

The installation commands provided here were tested on MacOS, but you shouldn't run into issues if you're working in the Windows command line or on a Linux machine. You will need access to a MongoDB instance already running.

Return to Top

Setting Up a Local Laravel Development Environment

(Feel free to code along or to download the full code from this GitHub repo.)

Prerequisites

Since Laravel is a PHP framework, you will need to have PHP installed on your computer. The procedure may vary depending on your operating system. For more details on this step, please see the official installation documentation. For our walkthrough, you will need PHP version 7.4 installed on your computer.

The next step is to install Composer. Composer is a library and dependency manager for PHP, allowing you to add libraries that you may want to use in your project.

Install the Laravel Project

Once you have PHP and Composer installed, you can install Laravel.

From a terminal window, enter the following command:

To start a Laravel project, run the following command. For our project, we'll use myapp as the name of our application:

This creates a folder called myapp, with the initial Laravel project structure inside of it.

If you run the following command from the myapp folder, you should see a web application running with the initial Laravel page at http://localhost:8000:

Install the Laravel MongoDB Package

Before we can install the MongoDB libraries for Laravel, we need to install the PHP extension for MongoDB. Run the following command:

You will also need to ensure that the mongodb extension is enabled in your php.ini file. The location of your php.ini file will vary depending on your operating system. Add the following line to your php.ini file:

Lastly, run the following command from your Laravel project directory in order to add the MongoDB package for Laravel:

Return to Top

Configuring Your Laravel Project to Use MongoDB

Configure MongoDB Database

In order for Laravel to communicate with your MongoDB database, you will need to add your database connection information to the config\database.php file under the “connections” object in your Laravel project as shown in this example:

 

Make sure to include the correct authentication information.

Set the default database connection name in config\database.php:

Define Providers

If your Laravel project does not load dependencies automatically, you may also need to add the following to the provider’s section in your app.php file:

Return to Top

Laravel MongoDB CRUD example

Laravel’s Eloquent library allows us to map and perform database CRUD operations (Create, Read, Update, Delete) directly from the Laravel models.

Assuming that we have a MongoDB collection called “posts,” an example document in the "posts" collection might look something like this:

If you are using MongoDB Atlas, you can use the Atlas Console to insert this document record directly into the database named “myappdb.”

Create a Model, Controller, Route, and a View File

Our first step will be to create a Laravel model to represent the blog posts. From the project directory, run the following command:

This will create an App/Models/Post.php and an App/Http/Controllers/PostController.php file.

By default, artisan creates models that extend Illuminate\Database\Eloquent\Model.

However, for MongoDB, we want to extend the MongoDB Eloquent model, so we want to edit App/Models/Post.php. Our Post model ought to look like this:

Note that when storing new data, Laravel will automatically create the collection in the MongoDB database for you. By default, the collection name is the plural of the model used (“posts” in this case). However, you can override that by setting a collection property on the model like this:

If you were using multiple databases, you would also want to specify the database connection name on the model as indicated above.

Next, we can use our Post model to read and display our blog posts from the MongoDB database. First, let’s create a function in the PostController to get a blog post using a slug:

In the example above, we are just retrieving the post using its slug name. The MongoDB Eloquent models support all the standard Eloquent query methods, but they also support additional queries that are specific to MongoDB itself. For more details, see https://github.com/mongodb/laravel-mongodb.

Next, let’s add the following line to the routes\web.php file to create a route for the blog posts:

 

Return to Top

Display the Data Using the Laravel View

Finally, let’s add a view to format and style the blog post data for display. The view name needs to match the view that we use in our controller. We can do this by creating the file myapp/resources/views/post.blade.php with the following content:

Now we can see our post at http://localhost:8000/post/first-blog-post.

Save the Data into the MongoDB Database

Now, let’s say you also wanted to create an API that you could use to create blog posts in your application. First, we would want to add a method in our PostController to store a post:

Next, we want to configure a resource route for posts in App\routes\api.php:

And finally, we can test our API by making a POST request to http://localhost:8000/api/posts. Here’s an example using the Postman app:

Document

We can check the MongoDB database and see the blog post has been stored:

We should also be able to see the new post by going to http://localhost:8000/post/second-blog-post.

Return to Top

Deleting Data From the Database

As you may have noticed, if a primary key is not specified on the model, the property _id is used as the primary key for each record.

To delete a record, we can use that id to find and delete records. Since we already defined a resource route for posts, we only need to add a destroy() method to the PostController:

Then, we can issue a DELETE request to the API endpoint http://localhost:8000/api/posts/ to delete a post.

Updating Data in the Database

We have created APIs to create and delete blog posts. We may also want to create an API for updating blog posts. This is very similar to the previous examples. We just need to add a method to the PostController:

Now, we can issue a PUT request to the API endpoint http://localhost:8000/api/posts/ with the updated content of the blog post.

Return to Top

Summary

FAQ

Get started with Atlas today

Get started in seconds. Our free clusters come with 512 MB of storage so you can play around with sample data and get oriented with our platform.
Try FreeContact sales
GET STARTED WITH:
  • 125+ regions worldwide
  • Sample data sets
  • Always-on authentication
  • End-to-end encryption
  • Command line tools