MongoDB and Laravel Integration

Connect MongoDB to Laravel in minutes with Atlas.

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’s document model makes it a great database choice for web applications because its flexible schema structure will easily evolve to meet your growing needs.

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.

Benefits of Using MongoDB Atlas

When developing a web application, you don’t want to spend a lot of time setting up and maintaining a database. Your local server may also have limited resources for storing data. MongoDB Atlas—MongoDB offered as a cloud service—is a great solution for this problem. You can create your cluster and database from a web console and connect to it from your Laravel application in just minutes. Atlas offers a free tier to get started with your Atlas experience.

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:

composer global require "laravel/installer"
export PATH=$PATH:$HOME/.composer/vendor/bin

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

laravel new myapp

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:

cd myapp
php artisan serve

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:

sudo pecl install mongodb

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:

extension="mongodb.so"

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

composer require jenssegers/mongodb

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:

'connections' => [
  mongodb' => [
        'driver' => 'mongodb',
        'dsn' => env('DB_URI', 'mongodb+srv://username:password@<atlas-cluster-uri>/myappdb?retryWrites=true&w=majority'),
        'database' => 'myappdb',
],

Make sure to include the correct authentication information.

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

   /*
    |--------------------------------------------------------------------------
| Default Database Connection Name
    |--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
    */

'default' => env('DB_CONNECTION', 'mongodb'),

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:

'providers' => [

/*
* Laravel Framework Service Providers...
*/

Jenssegers\Mongodb\MongodbServiceProvider::class,

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:

{ 
   "title":"First Blog Post",
   "body" :"Lorem Ipsum, etc.",
   "slug" :"first-blog-post"
}

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:

php artisan make:model Post -mc

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:

namespace App\Models;

use Jenssegers\Mongodb\Eloquent\Model;

class Post extends Model
{
   protected $connection = 'mongodb';

}

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:

protected $collection = 'blog_posts';

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:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
   public function show($slug)
   {
       return view('post', [
           'post' => Post::where('slug', '=', $slug)->first()
       ]);
   }

}

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/jenssegers/laravel-mongodb.

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

Route::get('/post/{slug}', [PostController::class, 'show']);
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/post/{slug}', [PostController::class, 'show']);

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:

<!DOCTYPE html>
<html>
<head>
   <title>MyBlog</title>
</head>
<body>
   <h1>{{$post->title}}</h1>
   <div>{{$post->body}}</div>
</body>
</html>

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:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Post;

class PostController extends Controller
{
   public function show($slug)
   {
       return view('post', [
           'post' => Post::where('slug', '=', $slug)->first()
       ]);
   }

   public function store(Request $request)
   {
       $post = new Post;

       $post->title = $request->title;
       $post->body = $request->body;
       $post->slug = $request->slug;

       $post->save();

       return response()->json(["result" => "ok"], 201);
   }

}

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

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PostController;

Route::resource('posts', PostController::class)->only([
   'destroy', 'show', 'store', 'update'
]);

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

{
  "title" : "Second Post",
  "body" : "This is my second post.",
  "slug" : "second-blog-post"
}

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.

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:

public function destroy($postId)
 {
     $post = Post::find($postId);
     $post->delete();

     return response()->json(["result" => "ok"], 200);       
 }

Then, we can issue a DELETE request to the API endpoint http://localhost:8000/api/posts/<post_id> 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:

 public function update(Request $request, $postId)
   {
       $post = Post::find($postId);
       $post->title = $request->title;
       $post->body = $request->body;
       $post->slug = $request->slug;
       $post->save();

       return response()->json(["result" => "ok"], 201);       
   }

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

Summary

  • In this article, we have shown how quickly you can get a Laravel application up and running, using MongoDB as a data store.
  • Unlike relational databases like MySQL, you don’t need to worry about creating and maintaining database migrations. You can use the same Eloquent model functionality that you may already be familiar with.
  • You can also take advantage of the additional querying capabilities that MongoDB provides.
  • If you're a PHP developer, consider using Laravel with MongoDB for your next app.

Ready to get started?

Launch a new cluster or migrate to MongoDB Atlas with zero downtime.

Does Laravel support MongoDB?

Yes. The Laravel-MongoDB library integrates very well into the Laravel Eloquent model and allows developers to use MongoDB without additional effort.

How does MongoDB connect to Laravel?

You would configure the database connection the same way you would for other databases in the config/database.php file. If your Laravel configuration uses multiple databases, you would also specify the connection to use on the Laravel models.

Can I use MongoDB with Laravel?

Yes, MongoDB is a great choice to use with Laravel. The Laravel-MongoDB library integrates very well into the Laravel Eloquent model and allows developers to use MongoDB without additional effort.

Which database is best for Laravel?

There is no single best database for all types of applications. However, MongoDB is a great choice to start with since it does not require schema maintenance and migrations, as you would need with relational databases like MySQL, MariaDB, or Postgresql.

Can you use MongoDB with PHP?

Yes, MongoDB has a PHP driver that can be used directly from PHP. For most applications, you may want to use it through a framework like Laravel since it will minimize the amount of coding required.

When should I use MongoDB?

MongoDB can be used in most types of applications. Its flexible schema approach makes it a great choice for building small applications where the data model evolves over time. It also scales well, making it a great choice for large volumes of data.

Can Laravel connect to multiple MongoDB databases?

Yes, Laravel supports connecting to multiple databases. Each database connection needs to be defined in the config/dartabase.php file. Laravel can talk to multiple MongoDB databases or a mix of MongoDB and other databases as well.