ServerAvatar Logo

How to Connect Laravel with MongoDB Easily in 2025

  • Author: Suresh Ramani
  • Published: 9 August 2025
  • Last Updated: 8 August 2025
MongoDB Laravel

Table Of Contents

Are you tired of wrestling with traditional SQL databases and looking for something more flexible? Laravel MongoDB is like the Swiss Army knife of databases – versatile, powerful, and perfect for modern web applications. When you pair it with Laravel’s elegant framework, you get a combination that’s like peanut butter and jelly for developers.

In today’s fast-paced development world, NoSQL databases like MongoDB have become increasingly popular. Why? Because they offer the flexibility that traditional relational databases simply can’t match. Whether you’re building a content management system, an e-commerce platform, or a social media application, MongoDB Laravel integration can give you the scalability and performance you need.

Understanding MongoDB and Laravel Compatibility

Before we dive into the technical details, let’s address the elephant in the room: Can Laravel work seamlessly with MongoDB? The short answer is yes, but it requires some additional setup.

Laravel’s Native Database Support Laravel was built with SQL databases in mind. Out of the box, it supports MySQL, PostgreSQL, SQLite, and SQL Server. However, with the right packages and configuration, you can make Laravel work beautifully with MongoDB.

Why Choose MongoDB for Your Laravel Project? MongoDB offers several advantages that make it an attractive choice for modern web applications:

  • Flexible Schema: No need to define rigid table structures
  • Horizontal Scalability: Easy to scale across multiple servers
  • JSON-like Documents: Perfect for storing complex data structures
  • High Performance: Optimized for read and write operations

The Bridge: Official Laravel MongoDB Package The official solution for connecting Laravel with MongoDB is the mongodb/laravel-mongodb package (formerly named jenssegers/mongodb). This package is now owned and maintained by MongoDB, Inc. and is compatible with Laravel 10.x and later. This package acts as a bridge, translating Laravel’s Eloquent ORM calls into MongoDB operations while providing native MongoDB features like TTL indexes and GridFS support.

Prerequisites and System Requirements

Before you start your MongoDB Laravel journey, make sure you have everything in place. Think of this as checking your toolkit before starting a DIY project.

Software Requirements:

  • PHP 7.4 or higher (PHP 8+ recommended)
  • Laravel 8.0 or higher
  • MongoDB 4.0 or higher
  • Composer package manager

System Dependencies:

  • MongoDB PHP extension
  • OpenSSL extension
  • Mbstring extension
  • Tokenizer extension

Development Environment Setup Whether you’re using XAMPP, WAMP, Laravel Sail, or Docker, ensure your environment supports both Laravel and MongoDB. If you’re using a local development stack, you might need to install MongoDB separately.

Installing MongoDB Extension for PHP

Getting the MongoDB PHP extension up and running is your first technical hurdle. Don’t worry – it’s easier than it sounds!

For Windows Users:

  1. Download the appropriate MongoDB PHP extension from PECL
  2. Extract the php_mongodb.dll file to your PHP extensions directory
  3. Add extension=mongodb to your php.ini file
  4. Restart your web server

For macOS Users:

Bash
# Using Homebrew
brew install mongodb/brew/mongodb-community
pecl install mongodb

For Linux Users:

Bash
# Ubuntu/Debian
sudo apt-get install php-mongodb

# CentOS/RHEL
sudo yum install php-mongodb

Verifying Installation After installation, verify that the extension is loaded:

PHP
<?php
if (extension_loaded('mongodb')) {
    echo "MongoDB extension is loaded!";
} else {
    echo "MongoDB extension is NOT loaded!";
}
?>

Setting Up Laravel MongoDB Package

Now comes the fun part – installing the Laravel MongoDB package that will make your life much easier.

Installing the Package Open your terminal in your Laravel project directory and run:

Bash
composer require mongodb/laravel-mongodb

Important Note: This installation will fail if the mongodb PHP extension is not installed. Make sure you have completed the previous step before proceeding.

Service Provider Registration For Laravel 10.x and later, service provider auto-discovery is enabled by default, so no manual registration is required. The package will automatically register its service providers.

Publishing Configuration While not mandatory, you can publish the MongoDB configuration file:

Bash
php artisan vendor:publish --provider="MongoDB\Laravel\MongoDBServiceProvider"

This creates a config/mongodb.php file where you can customize advanced settings.

Configuring Database Connections

Configuration is where the rubber meets the road. Get this right, and everything else flows smoothly.

Database Configuration Open your config/database.php file and add the MongoDB connection. Laravel now supports a simplified DSN-based configuration:

PHP
'connections' => [
    // Existing connections...
    
    'mongodb' => [
        'driver' => 'mongodb',
        'dsn' => env('MONGODB_URI', 'mongodb://localhost:27017'),
        'database' => env('MONGODB_DATABASE', 'laravel_app'),
    ],
],

Environment Variables Update your .env file with your MongoDB connection details:

Plaintext
MONGODB_URI="mongodb://localhost:27017"
MONGODB_DATABASE="laravel_app"

# For MongoDB Atlas (cloud)
# MONGODB_URI="mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<dbname>?retryWrites=true&w=majority"

Setting Default Connection You can set MongoDB as your default database connection:

Plaintext
DB_CONNECTION=mongodb

MongoDB Atlas Configuration For cloud hosting with MongoDB Atlas, use the connection string format:

Plaintext
MONGODB_URI="mongodb+srv://<username>:<password>@<cluster>.mongodb.net/<dbname>?retryWrites=true&w=majority"
MONGODB_DATABASE="laravel_app"

Creating MongoDB Models in Laravel

Creating models for MongoDB is similar to creating regular Eloquent models, with a few key differences.

Basic Model Structure Instead of extending Illuminate\Database\Eloquent\Model, your MongoDB models should extend MongoDB\Laravel\Eloquent\Model:

PHP
<?php

namespace App\Models;

use MongoDB\Laravel\Eloquent\Model;

class User extends Model
{
    protected $connection = 'mongodb';
    protected $collection = 'users';
    
    protected $fillable = [
        'name', 'email', 'age', 'preferences'
    ];
}

Key Differences from SQL Models:

  • Use $collection instead of $table
  • MongoDB documents can have nested arrays and objects
  • No need for strict schema definitions

Working with Nested Data One of MongoDB’s strengths is handling complex nested data:

PHP
class Product extends Model
{
    protected $connection = 'mongodb';
    protected $collection = 'products';
    
    protected $fillable = [
        'name', 'price', 'specifications', 'reviews'
    ];
    
    protected $casts = [
        'specifications' => 'array',
        'reviews' => 'array',
    ];
}

Working with Collections and Documents

In MongoDB, tables are called collections, and rows are called documents. Think of documents as JSON objects that can contain arrays, nested objects, and various data types.

Creating Documents Creating new documents is straightforward:

PHP
use App\Models\User;

$user = new User();
$user->name = 'John Doe';
$user->email = 'john@example.com';
$user->preferences = [
    'theme' => 'dark',
    'notifications' => true,
    'languages' => ['en', 'es']
];
$user->save();

Mass Assignment You can also use mass assignment:

PHP
User::create([
    'name' => 'Jane Smith',
    'email' => 'jane@example.com',
    'profile' => [
        'bio' => 'Software developer',
        'location' => 'New York',
        'skills' => ['PHP', 'JavaScript', 'MongoDB']
    ]
]);

Querying Documents Querying works similarly to regular Eloquent:

PHP
// Find by ID
$user = User::find('60d5ec49f8b6c8001f5e4b12');

// Where clauses
$users = User::where('age', '>', 25)->get();

// Nested queries
$developers = User::where('profile.skills', 'PHP')->get();

Database Migrations in MongoDB

While MongoDB is schema-less, you might still want to use migrations for data transformations or index creation.

Creating Migrations Generate a migration file:

Bash
php artisan make:migration create_users_collection

Migration Structure Here’s how a MongoDB migration might look:

PHP
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersCollection extends Migration
{
    public function up()
    {
        Schema::connection('mongodb')->create('users', function (Blueprint $collection) {
            $collection->index('email');
            $collection->index('created_at');
        });
    }
    
    public function down()
    {
        Schema::connection('mongodb')->drop('users');
    }
}

Index Management Creating indexes is crucial for performance:

PHP
// In your migration
$collection->index('email', null, null, ['unique' => true]);
$collection->index(['name' => 'text', 'bio' => 'text']); // Text search

Eloquent Queries with MongoDB

The beauty of using the Laravel MongoDB package is that most Eloquent methods work seamlessly with MongoDB.

Basic Queries

PHP
// Select all users
$users = User::all();

// Find specific users
$user = User::where('email', 'john@example.com')->first();

// Count documents
$userCount = User::count();

// Pagination
$users = User::paginate(10);

Advanced Queries MongoDB’s flexibility shines with complex queries:

PHP
// Array contains
$phpDevelopers = User::where('skills', 'PHP')->get();

// Nested object queries
$newYorkUsers = User::where('profile.location', 'New York')->get();

// Regular expressions
$gmailUsers = User::where('email', 'regex', '/gmail.com$/')->get();

// Date ranges
$recentUsers = User::whereBetween('created_at', [
    now()->subDays(30), 
    now()
])->get();

Aggregation Pipeline For complex data processing, you can use MongoDB’s aggregation pipeline:

PHP
$result = User::raw(function($collection) {
    return $collection->aggregate([
        ['$match' => ['age' => ['$gte' => 18]]],
        ['$group' => [
            '_id' => '$city',
            'count' => ['$sum' => 1],
            'avgAge' => ['$avg' => '$age']
        ]]
    ]);
});

Relationships in MongoDB Laravel

Relationships in MongoDB work differently than in SQL databases, but the Laravel MongoDB package provides similar syntax.

Embedded Documents MongoDB excels at embedded relationships:

PHP
class Blog extends Model
{
    protected $connection = 'mongodb';
    
    protected $fillable = ['title', 'content', 'comments'];
    
    protected $casts = [
        'comments' => 'array'
    ];
}

// Creating a blog with embedded comments
Blog::create([
    'title' => 'My First Post',
    'content' => 'Lorem ipsum...',
    'comments' => [
        ['author' => 'John', 'text' => 'Great post!'],
        ['author' => 'Jane', 'text' => 'Thanks for sharing!']
    ]
]);

Referenced Relationships For normalized data, use referenced relationships:

PHP
class User extends Model
{
    protected $connection = 'mongodb';
    
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

class Post extends Model
{
    protected $connection = 'mongodb';
    
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Authentication with MongoDB

Setting up Laravel’s built-in authentication with MongoDB requires a few adjustments.

User Model Configuration Your User model should extend the MongoDB model while implementing the necessary contracts:

PHP
<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use MongoDB\Laravel\Eloquent\Model;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword;
    
    protected $connection = 'mongodb';
    protected $collection = 'users';
    
    protected $fillable = [
        'name', 'email', 'password',
    ];
    
    protected $hidden = [
        'password', 'remember_token',
    ];
}

Authentication Configuration Update config/auth.php to use your MongoDB user provider:

PHP
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],
],

Performance Optimization Tips

Performance is crucial for any database integration. Here are some MongoDB Laravel optimization strategies:

Indexing Strategy

  • Create indexes on frequently queried fields
  • Use compound indexes for multi-field queries
  • Monitor slow queries and add appropriate indexes

Query Optimization

PHP
// Use select() to limit returned fields
$users = User::select('name', 'email')->get();

// Use lazy loading for large datasets
User::chunk(100, function ($users) {
    foreach ($users as $user) {
        // Process user
    }
});

// Cache frequently accessed data
$popularPosts = Cache::remember('popular_posts', 3600, function () {
    return Post::where('views', '>', 1000)->get();
});

Connection Pooling Configure connection pooling in your MongoDB connection settings to handle concurrent requests efficiently.

Common Troubleshooting Issues

Every developer faces challenges. Here are solutions to common MongoDB Laravel problems:

Issue 1: Extension Not Loaded

Bash
# Check if extension is installed
php -m | grep mongodb

# Install if missing
pecl install mongodb

Issue 2: Connection Timeouts Increase timeout values in your connection configuration:

PHP
'mongodb' => [
    'driver' => 'mongodb',
    // ... other config
    'options' => [
        'connectTimeoutMS' => 60000,
        'socketTimeoutMS' => 60000,
    ],
],

Issue 3: Memory Limit Exceeded For large datasets, use chunking or streaming:

PHP
User::chunk(1000, function ($users) {
    foreach ($users as $user) {
        // Process in batches
    }
});

Best Practices for Production

Running MongoDB Laravel in production requires careful consideration:

Security Best Practices

  • Enable authentication and authorization
  • Use SSL/TLS for connections
  • Implement proper user roles and permissions
  • Regularly update MongoDB and PHP extensions

Monitoring and Logging

  • Set up MongoDB monitoring tools
  • Log slow queries for optimization
  • Monitor connection pool usage
  • Track application performance metrics

Backup Strategy

  • Implement regular automated backups
  • Test backup restoration procedures
  • Use replica sets for high availability
  • Consider geographic distribution for disaster recovery

Alternative Packages and Tools

While jenssegers/mongodb is the most popular choice, there are alternatives:

Alternative Packages:

  • Laravel MongoDB: The official mongodb/laravel-mongodb package (recommended)
  • Direct MongoDB PHP Library: Using MongoDB PHP library without Laravel integration
  • Custom Implementation: Building custom MongoDB integration for specific needs

Official Resources and Documentation: For comprehensive learning and reference, check out these authoritative resources:

Development Tools:

  • MongoDB Compass: GUI for database management
  • Studio 3T: Advanced MongoDB IDE
  • Laravel Telescope: For monitoring database queries

When to Consider Alternatives:

  • Need for specific MongoDB features not supported
  • Performance requirements that demand direct driver usage
  • Custom implementation requirements

Conclusion

Connecting MongoDB Laravel doesn’t have to be a daunting task. With the right setup, configuration, and understanding of MongoDB’s document-based nature, you can build powerful, scalable applications that leverage the best of both worlds.

Remember, the key to success lies in understanding that MongoDB thinks differently than traditional SQL databases. Embrace the flexibility of document storage, design your data models accordingly, and you’ll discover why so many developers are making the switch to NoSQL solutions.

Whether you’re building a small personal project or a large-scale enterprise application, the MongoDB Laravel combination provides the tools and flexibility you need to succeed in 2025 and beyond.

Frequently Asked Questions

Can I use both MySQL and MongoDB in the same Laravel application?

Yes, you can use multiple database connections simultaneously in Laravel. Simply configure both connections in your config/database.php file and specify the connection in your models using the $connection property.

Is the Laravel MongoDB package compatible with the latest Laravel versions?

The jenssegers/mongodb package is actively maintained and supports Laravel 8.x and 9.x. However, always check the package documentation for the most current compatibility information before upgrading Laravel versions.

How do I handle file uploads with MongoDB in Laravel?

For file storage, you can use Laravel’s filesystem abstraction with cloud storage services, while storing file metadata (path, size, mime type) in MongoDB documents. Alternatively, use MongoDB GridFS for storing large files directly in the database.

What’s the performance difference between MongoDB and MySQL with Laravel?

Performance depends on your use case. MongoDB excels with complex nested data, horizontal scaling, and read-heavy workloads. MySQL performs better for complex relational queries and transactions. Benchmark both with your specific data patterns.

Can I use Laravel’s built-in authentication and authorization features with MongoDB?

Yes, Laravel’s authentication system works with MongoDB when you properly configure your User model to extend the MongoDB Eloquent model while implementing the necessary authentication contracts. You may need to adjust some middleware and guards for optimal compatibility.

Deploy your first application in 10 minutes, Risk Free!

Learn how ServerAvatar simplifies server management with intuitive dashboards and automated processes.
  • No CC Info Required
  • Free 4-Days Trial
  • Deploy in Next 10 Minutes!