Getting Started with MongoDB in Laravel 12: A Complete Beginnerās Guide
š§² Imagine Thisā¦
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. š
š§° What Is MongoDB (in Simple Terms)?
MongoDB is a NoSQL database that stores data in JSON-like documents. That means:
- No predefined schemas (you donāt need to define every column)
- You can store arrays, nested documents, and complex types
- You can retrieve and update just as flexibly
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.
š¦ Why Use MongoDB with Laravel?
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.
š§Ŗ Step 1: Prerequisites
Before we dive in, make sure you have:
- Laravel 12 installed
- PHP >= 8.1
- Composer
- MongoDB installed locally or a MongoDB Atlas account
š§© Installing MongoDB PHP Extension
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).
š Step 2: Installing the MongoDB Laravel Package
In your Laravel project root, run:
composer require mongodb/laravel-mongodb
This package integrates MongoDB into Laravelās Eloquent ORM and query builder.
āļø Step 3: Configuration
.env Setup
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
config/database.php
Add a new connection:
'mongodb' => [
'driver' => 'mongodb',
'dsn' => env('MONGODB_URI'),
'database' => env('MONGODB_DATABASE'),
],
Set it as default (optional):
DB_CONNECTION=mongodb
š§± Step 4: Creating Your First MongoDB Model
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.
š§ Step 5: CRUD Operations (The Laravel Way)
Create a Document
Post::create([
'title' => 'My First Post',
'content' => 'Hello MongoDB!',
'tags' => ['laravel', 'nosql']
]);
Read Documents
$posts = Post::where('tags', 'laravel')->get();
Update
$post = Post::first();
$post->update(['content' => 'Updated content']);
Delete
Post::where('title', 'My First Post')->delete();
ā Just like MySQL, but more flexible!
𧬠Step 6: Embedded Documents (Nested Data)
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);
}
}
Add a Comment
$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.
š Step 7: Raw Queries & Aggregations
Aggregation Pipeline Example
$pipeline = [
['$match' => ['tags' => 'laravel']],
['$group' => ['_id' => '$tags', 'count' => ['$sum' => 1]]]
];
$results = Post::raw(function ($collection) use ($pipeline) {
return $collection->aggregate($pipeline);
});
š§ Step 8: Advanced Features
šļø Cache Driver
Use MongoDB as your cache store in config/cache.php:
'default' => 'mongodb',
Set TTL index for expiration.
š¬ Queue Driver
Use MongoDB as your queue backend with:
QUEUE_CONNECTION=mongodb
Jobs are stored in a Mongo collection and processed normally.
š§¾ File Storage with GridFS
GridFS lets you store large files in MongoDB. Configure it via Laravel Filesystem:
'disks' => [
'gridfs' => [
'driver' => 'mongodb',
'bucket' => 'my_files'
],
],
š§ Common Pitfalls & Fixes
| 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 |
šÆ Use Cases
MongoDB is perfect for:
- š Analytics & logs
- š Real-time dashboards
- š§ AI metadata storage
- š· File-heavy apps (with GridFS)
- š E-commerce with dynamic products
š§¾ Recap: MongoDB + Laravel 12
ā
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
š Your Turn!
Youāve got the tools. Now itās time to build. Here are some ideas to try:
- Create a nested comment system for a blog
- Store product variations using flexible schemas
- Upload user files using GridFS
- Mix MongoDB + MySQL in the same app for hybrid architecture
Laravel 12 and MongoDB together give you the best of both worlds: developer ergonomics and modern database power.
š FAQ (Beginners Ask These A Lot)
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.
Let's Chat
What are you planning to build with Laravel and MongoDB?
Drop a comment belowāIād love to help or hear your ideas!
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
š Featuresā Google & GitHub Authenticationā User Registration & Loginā Profile/Dashboard Accessā Secure & Mi...
Flask Blog CMS with Admin Dashboard ā Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
š Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.