How to Install MongoDB and Use It with Laravel for CRUD Operations
This tutorial explains how to install the MongoDB server, add the PHP MongoDB extension, configure Laravel to connect to MongoDB, and implement full CRUD operations using a custom Eloquent model and controller.
MongoDB is a distributed, document‑oriented database written in C++ that supports schema‑less data modeling.
This guide shows how to install the MongoDB server on Windows, add the PHP MongoDB extension, and integrate MongoDB with a Laravel application.
First, download and install MongoDB from the official website, then copy the compiled mongodb.so (or the appropriate DLL) into the PHP extensions directory and enable it in php.ini .
Next, install the Laravel MongoDB package via Composer:
composer require jenssegers/mongodbRegister the service provider Jenssegers\Mongodb\MongodbServiceProvider::class in config/app.php and add a MongoDB connection configuration to config/database.php with keys such as DB_CONNECTION=mongodb , MONGODB_HOST=127.0.0.1 , MONGODB_PORT=27017 , MONGODB_DB=laravel , MONGODB_USERNAME=admin , MONGODB_PASSWORD=123456 , etc.
Create an Eloquent model that extends Jenssegers\Mongodb\Eloquent\Model and set the protected $connection = 'mongodb' and $fillable = ['name','age','sex'] fields.
Implement a controller with methods for creating, reading, updating, and deleting documents using the model’s query() builder, e.g., Animal::query()->create($data) , Animal::query()->where('name','狗')->first() , Animal::query()->where('_id',$id)->update(['name'=>'小狗']) , and Animal::query()->where('_id',$id)->delete() .
After following these steps, the Laravel application can perform full CRUD operations on MongoDB collections.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.