Kritim Yantra
Jul 12, 2025
You're building an app. Your users can create profiles, post comments, upload photos, and maybe even store settings or preferences that vary from user to user. Suddenly, you're dealing with complex data that doesn’t fit neatly into tables. Fields vary. Relationships nest. Migrations multiply.
Traditional SQL databases start to feel like trying to write a novel on a typewriter.
What if you could store and retrieve flexible, evolving data models with ease?
That’s where MongoDB shines.
And the best part? You don’t need to ditch Laravel. With Laravel 12’s MongoDB support, you can use Eloquent, Query Builder, and even queues and caching—without sacrificing performance or developer happiness.
Let’s dive in. 🌊
MongoDB is a NoSQL database that stores data in JSON-like documents. That means:
In contrast to SQL databases (like MySQL), MongoDB is optimized for scalability, real-time applications, and schema-less data.
🧠 Think of MongoDB as a big, flexible filing cabinet of documents. Need to add a new field? Just write it in. No migrations, no table rewrites.
Laravel traditionally works with SQL databases, but modern apps need flexibility. MongoDB offers:
✅ Schema-less design: Perfect for evolving projects
✅ Document embedding: Nest related data instead of joining tables
✅ High scalability: Great for IoT, analytics, logs, etc.
✅ Built-in support for queues, caching, sessions using MongoDB TTL indexes
✅ GridFS: Store and retrieve large files like videos, PDFs, and images
And with the official MongoDB Laravel package, you don’t need to learn a new framework. You just extend what you already know.
Before we dive in, make sure you have:
pecl install mongodb
Then add this to your php.ini
:
extension=mongodb.so
Verify it’s installed:
php -m | grep mongodb
📝 Tip: You must install it for both CLI and web server (FPM or Apache).
In your Laravel project root, run:
composer require mongodb/laravel-mongodb
This package integrates MongoDB into Laravel’s Eloquent ORM and query builder.
MONGODB_URI=mongodb://localhost:27017
MONGODB_DATABASE=my_laravel_app
For MongoDB Atlas:
MONGODB_URI=mongodb+srv://<username>:<password>@cluster.mongodb.net/my_laravel_app
MONGODB_DATABASE=my_laravel_app
Add a new connection:
'mongodb' => [
'driver' => 'mongodb',
'dsn' => env('MONGODB_URI'),
'database' => env('MONGODB_DATABASE'),
],
Set it as default (optional):
DB_CONNECTION=mongodb
use MongoDB\Laravel\Eloquent\Model;
class Post extends Model
{
protected $connection = 'mongodb';
protected $collection = 'posts';
protected $fillable = ['title', 'content', 'tags'];
}
📝 The collection name is the MongoDB equivalent of a table.
Post::create([
'title' => 'My First Post',
'content' => 'Hello MongoDB!',
'tags' => ['laravel', 'nosql']
]);
$posts = Post::where('tags', 'laravel')->get();
$post = Post::first();
$post->update(['content' => 'Updated content']);
Post::where('title', 'My First Post')->delete();
✅ Just like MySQL, but more flexible!
Let’s say each post has comments:
class Comment extends Model
{
protected $fillable = ['author', 'message'];
}
class Post extends Model
{
public function comments()
{
return $this->embedsMany(Comment::class);
}
}
$post = Post::first();
$post->comments()->create([
'author' => 'John Doe',
'message' => 'Great post!'
]);
Now the comment is stored inside the post document.
🧠 This is more efficient than foreign keys + joins in many cases.
$pipeline = [
['$match' => ['tags' => 'laravel']],
['$group' => ['_id' => '$tags', 'count' => ['$sum' => 1]]]
];
$results = Post::raw(function ($collection) use ($pipeline) {
return $collection->aggregate($pipeline);
});
Use MongoDB as your cache store in config/cache.php
:
'default' => 'mongodb',
Set TTL index for expiration.
Use MongoDB as your queue backend with:
QUEUE_CONNECTION=mongodb
Jobs are stored in a Mongo collection and processed normally.
GridFS lets you store large files in MongoDB. Configure it via Laravel Filesystem:
'disks' => [
'gridfs' => [
'driver' => 'mongodb',
'bucket' => 'my_files'
],
],
Problem | Solution |
---|---|
Class not found: MongoDB\Client |
Install mongodb PHP extension |
Collections not showing | MongoDB creates collections lazily—insert something first |
Can't connect to Atlas | Whitelist your IP in Atlas dashboard |
Schema errors | You don't need strict schema—Mongo is flexible |
MongoDB is perfect for:
✅ Easy setup with mongodb/laravel-mongodb
✅ Supports Eloquent, Query Builder, raw driver
✅ Perfect for schema-less, embedded data
✅ Integrates with queues, caching, and file storage
✅ Ideal for modern, scalable applications
You’ve got the tools. Now it’s time to build. Here are some ideas to try:
Laravel 12 and MongoDB together give you the best of both worlds: developer ergonomics and modern database power.
Q1: Do I need to run migrations for MongoDB?
A: Not unless you need indexes. Collections are created on the fly.
Q2: Can I use MongoDB and MySQL together in Laravel?
A: Yes! You can define multiple connections and assign them to different models.
Q3: Can I run full-text or geospatial searches?
A: Absolutely. MongoDB supports both via special indexes.
What are you planning to build with Laravel and MongoDB?
Drop a comment below—I’d love to help or hear your ideas!
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google