How to easily integrate MongoDB into Laravel

Diego Cortés
Diego Cortés
January 21, 2025
How to easily integrate MongoDB into Laravel

Integrating MongoDB into Laravel may seem challenging at first, especially if you are used to working with SQL databases. However, Laravel offers tools and libraries that greatly simplify this process. In this article, we will show you how to do it in a straightforward and clear manner.

What is MongoDB?

MongoDB is a NoSQL document-oriented database that uses a flexible data model. It stores data in BSON documents, allowing for a more dynamic structure than traditional relational databases. These features make MongoDB an excellent choice for applications that require high scalability and flexibility.

Prerequisites

Before you begin, make sure you have installed:

  • PHP (preferably version 7.4 or higher)
  • Composer for managing Laravel dependencies
  • Laravel (version 8.x or higher)
  • MongoDB on your local machine or access to a MongoDB server

Installing the MongoDB Extension for PHP

To enable Laravel to interact with MongoDB, you need to install the PHP extension for MongoDB. If you are using Composer, you can do it with the following command:

sudo pecl install mongodb

Make sure the extension is enabled in your php.ini file by adding the following line:

extension=mongodb.so

After doing this, restart your web server.

Configuring Laravel to Use MongoDB

Step 1: Install the MongoDB package for Laravel

Laravel does not include native support for MongoDB, so we will use an external package called jenssegers/mongodb. To install it, run the following command in the terminal within your Laravel directory:

composer require jenssegers/mongodb

Step 2: Configure the connection file

Once the package is installed, you will need to configure the connection to your MongoDB database. Open the configuration file config/database.php and add the following configuration:

'mongodb' => [
    'driver'   => 'mongodb',
    'host'     => env('DB_HOST', 'localhost'),
    'port'     => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE'),
    'username' => env('DB_USERNAME'),
    'password' => env('DB_PASSWORD'),
    'options'  => [
        'database' => 'admin' // Database authentication (may vary)
    ]
],

You will also need to add your connection credentials in the .env file:

DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
DB_PORT=27017
DB_DATABASE=my_database
DB_USERNAME=my_user
DB_PASSWORD=my_password

Step 3: Create an Eloquent model for MongoDB

To interact with your MongoDB database, you will need to create models using Eloquent. Below is a basic example.

Run the following command to create a new model:

php artisan make:model Product

In the file app/Models/Product.php, extend the Jenssegers model:

namespace App\Models;

use Jenssegers\Mongodb\Eloquent\Model;

class Product extends Model
{
    protected $connection = 'mongodb'; // Define the connection to MongoDB
    protected $collection = 'products'; // Name of the collection

    protected $fillable = ['name', 'price', 'quantity']; // Fields that can be filled
}

Performing Basic Operations with MongoDB

Now that you have your model configured, let's perform some example operations.

Create a new document

To create a new product in your collection, you can use:

use App\Models\Product;

$product = new Product();
$product->name = 'T-Shirt';
$product->price = 19.99;
$product->quantity = 100;
$product->save();

Query documents

To query documents from your collection, you can use Eloquent methods:

$products = Product::all(); // Get all products

Update a document

For example, if you want to update the price of a T-Shirt:

$product = Product::find($id);
$product->price = 24.99;
$product->save();

Delete a document

To delete a product:

$product = Product::find($id);
$product->delete();

Conclusion

Integrating MongoDB in Laravel is a straightforward process thanks to the available tools and libraries. By following the steps we have outlined, you can create and manage a MongoDB database from your Laravel application with ease. Be sure to explore the documentation of Jenssegers for more details and advanced options.

This combination of technologies is ideal for building modern and scalable applications, allowing developers to take advantage of the best of both worlds: the flexibility of MongoDB and the elegance of Laravel. Start today developing applications with MongoDB in Laravel!

Article information

Published: January 21, 2025
Category: Laravel Tutorials
Reading time: 5-8 minutes
Difficulty: Intermediate

Key tips

1

Take your time to understand each concept before moving on to the next one.

2

Practice the examples in your own development environment for better understanding.

3

Don't hesitate to review the additional resources mentioned in the article.

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Frequently Asked Questions

Categories

Page loaded in 25.49 ms