Databases 4 min read

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.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
How to Install MongoDB and Use It with Laravel for CRUD Operations

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/mongodb Register 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CRUD
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.