Skip to main content

How to Setup MongoDB with Laravel

How to Setup MongoDB with Laravel (Quick Guide)

In modern web applications, developers often look for flexible and scalable database solutions — and that’s where MongoDB shines. Unlike traditional SQL databases, MongoDB stores data in a document-oriented format, making it ideal for projects that handle dynamic, unstructured, or rapidly evolving data. Integrating it with Laravel allows you to enjoy the power of MongoDB’s flexibility while still using Laravel’s elegant and expressive syntax.

This step-by-step guide walks you through the complete process of integrating MongoDB with a Laravel application using the official mongodb/laravel-mongodb package. You’ll learn how to install all required dependencies, properly configure your .env and database settings, and seamlessly perform basic CRUD (Create, Read, Update, Delete) operations with MongoDB — all while maintaining Laravel’s familiar Eloquent-style syntax. By the end, you’ll have a fully functional Laravel app connected to MongoDB, ready for development or production use.

๐Ÿ‘‰ View full project on GitHub


๐Ÿงฉ Prerequisites

  • PHP (compatible with your Laravel version)
  • Composer
  • MongoDB instance (local or MongoDB Atlas)

⚙️ Step 1 — Install the MongoDB Laravel Package

Install the MongoDB driver for Laravel via Composer:

composer require mongodb/laravel-mongodb

If you must bypass the PHP extension check (not recommended for production):

composer require mongodb/laravel-mongodb --ignore-platform-req=ext-mongodb

๐Ÿงพ Step 2 — Configure the .env File

Set your database connection details:

DB_CONNECTION=mongodb
MONGODB_URI="mongodb+srv://<username>:<password>@cluster0.mongodb.net"
MONGODB_DATABASE=laravel_mongo_demo

Replace <username>, <password>, and cluster/database names as needed.


๐Ÿ›  Step 3 — Update config/database.php

Add or update the MongoDB connection settings:

'mongodb' => [
    'driver'   => 'mongodb',
    'dsn'      => env('MONGODB_URI'),
    'database' => env('MONGODB_DATABASE'),
],

๐Ÿ“„ Step 4 — Create a Model and Use It

Create a model named Post:

php artisan make:model Post

Example CRUD operations using Eloquent-style syntax:

// Create a new document
App\Models\Post::create([
    'title'  => 'First Post',
    'body'   => 'Testing MongoDB with Laravel.',
    'author' => 'Admin',
    'status' => 'published',
]);

// Fetch all documents
App\Models\Post::all();

๐Ÿ’ป Step 5 — Quick Test with Artisan Tinker

Open Tinker to test your model:

php artisan tinker

Run the example create/fetch commands above to verify the connection.


⚡ Optional — Install the PHP MongoDB Extension

For better performance and full driver support, install the mongodb PHP extension.

  1. Install via PECL or your system’s package manager.
  2. On Windows (WAMP/XAMPP):
    • Download the correct MongoDB DLL from PECL.
    • Place it in your PHP ext folder (e.g., C:\wamp64\bin\php\\ext).
    • Add extension=mongodb in php.ini.
    • Restart your server and verify with:
php -m | find "mongodb"

๐Ÿž Troubleshooting

  • If php artisan tinker fails, ensure the MongoDB extension is enabled.
  • If connection fails, verify your MONGODB_URI and Atlas network settings.
  • Check logs at storage/logs/laravel.log for driver issues.

๐Ÿ“š References


✅ Conclusion

Connecting MongoDB with Laravel is simple and efficient with the mongodb/laravel-mongodb package. By configuring your environment and updating a few settings, you can start using MongoDB’s flexible schema and Eloquent-like features right away.

๐Ÿš€ Explore the full code here: Setup MongoDB with Laravel (GitHub)


Author: Rana Saha

Comments

Popular posts from this blog

How to Use L5-Swagger for API Documentation in Laravel

Integrating Swagger in Laravel: Annotations, JSON, and YAML What is Swagger? Swagger (OpenAPI) is a powerful tool for generating interactive API documentation. It helps developers understand and test your API easily. ✅ Step-by-Step Guide to Setup L5-Swagger 1. Install L5-Swagger Package composer require "darkaonline/l5-swagger" 2. Publish Config & View Files This command publishes the config file to config/l5-swagger.php : php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider" 3. Configure Swagger (Optional) Edit the file config/l5-swagger.php to update: API Title Base Path Directories to scan for annotations 4. Add Swagger Annotations Add these before your controller class: /** * @OA\Info( * version="1.0.0", * title="Your API Title", * description=...

How to Send Emails in Node.js using Nodemailer and Ethereal

How to Send Email in Node.js using Nodemailer Email functionality is essential in modern web applications. Whether you're sending confirmation emails, password resets, or notifications, Node.js with Nodemailer makes this simple. In this blog, we'll walk through setting up email sending using Node.js , Express , and Ethereal Email for testing. ๐Ÿงพ Prerequisites Node.js installed Basic knowledge of Express.js Internet connection ๐Ÿ“ Project Structure project-folder/ ├── index.js ├── .env ├── package.json └── app/ └── controller/ └── emailSendController.js ๐Ÿ“ฆ Step 1: Install Dependencies npm init -y npm install express nodemailer dotenv npm install --save-dev nodemon ๐Ÿ” Configure nodemon (Optional but Recommended) Update your package.json with a custom start script: "scripts": { "start": "nodemon index.js" } ๐Ÿ” Step 2: Create a .env File Create a .env file a...

Realtime Device Tracker using Node.js, Socket.IO & Leaflet

Realtime Device Tracker using Node.js, Socket.IO & Leaflet In this tutorial, you’ll learn how to build a realtime location tracking application that uses the browser’s GPS, Socket.IO for live communication, and Leaflet.js to display users on a map. ๐Ÿš€ Project Overview Backend: Node.js, Express.js, Socket.IO Frontend: HTML, Leaflet.js, Socket.IO client Features: Live GPS tracking, multi-user map, disconnect cleanup ๐Ÿ“ Folder Structure project-root/ ├── app.js ├── package.json ├── src/ │ ├── public/ │ │ ├── css/ │ │ │ └── style.css │ │ └── js/ │ │ └── script.js │ ├── routes/ │ │ └── routers.js │ ├── socket/ │ │ └── socketHandler.js │ └── views/ │ └── index.ejs ๐Ÿง  How It Works Each user shares their location using the browser's navigator.geolocation API. Location is sent to the server via Socket.IO . The server broadcasts each user’s position to all clien...