Laravel

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web applications. Laravel is a powerful PHP framework known for its elegant syntax and rich ecosystem for building web applications. Combining Laravel with MongoDB provides a robust and efficient way for Laravel developers to build modern web applications.

Laravel developers can take advantage of MongoDB’s powerful features through the official MongoDB PHP driver and the mongodb/laravel-mongodb package. This package enables Laravel applications to use MongoDB with Eloquent, Laravel’s ORM, and provides integration for caching, queued jobs, and file storage with GridFS.

Steps to Integrate MongoDB with Laravel:

Step 1: Install MongoDB PHP extension

Use the below command to install the MongoDB PHP extension

pecl install mongodb

Verify extension using the below command

php -m | grep mongodb

Step 2: Starting MongoDB Server

MongoDB Community Server can run locally on Windows, macOS, and Linux, or in Docker containers. Follow the (https://www.mongodb.com/docs/manual/installation/) to get started.

Configure your .env file for local or cloud-hosted MongoDB:

MONGODB_URI="mongodb://localhost:27017"
MONGODB_DATABASE="laravel_app"

Step 3: Install the Laravel MongoDB Package

To install the Laravel MongoDB package, use the following command: 

composer require mongodb/laravel-mongodb

Configuration in Laravel

Go to config/database.php and add a new MongoDB Connection:

'connections' => [
    'mongodb' => [
        'driver' => 'mongodb',
        'dsn' => env('MONGODB_URI', 'mongodb://localhost:27017'),
        'database' => env('MONGODB_DATABASE', 'laravel_app'),
    ],
],

Using MongoDB with Laravel

Eloquent Models with MongoDB Collections

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Post extends Eloquent
{
    protected $connection = 'mongodb';
    protected $collection = 'posts';
}

Query Builder and Raw Queries

$posts = Post::where('status', 'published')->get();

Cache with MongoDB Cache Driver

Cache::put('key', 'value', 60);

Queue Jobs with MongoDB Queue Driver

You can queue jobs using MongoDB as a queue driver, enabling you to dispatch and process jobs efficiently.

File Storage with GridFS

MongoDB’s GridFS can store large files, such as images or videos, by breaking them into smaller chunks. Laravel’s GridFS Adapter integrates seamlessly with MongoDB for this purpose.

Storage::disk('gridfs')->put('file.txt', 'File content');

Example Application: Basic CRUD with MongoDB and Laravel

Step 1: Define a Model

Define a Post model connected to MongoDB:

use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class Post extends Eloquent
{
    protected $connection = 'mongodb';
    protected $collection = 'posts';
    protected $fillable = ['title', 'content', 'status'];
}

Step 2: Create a Controller

Set up a PostController to handle CRUD operations.

use App\Models\Post;

class PostController extends Controller
{
    public function create(Request $request)
    {
        $post = Post::create($request->all());
        return response()->json($post);
    }

    public function read($id)
    {
        $post = Post::find($id);
        return response()->json($post);
    }

    public function update(Request $request, $id)
    {
        $post = Post::find($id);
        $post->update($request->all());
        return response()->json($post);
    }

    public function delete($id)
    {
        Post::destroy($id);
        return response()->json('Post deleted successfully');
    }
}

Step 3: Set up Routes

Define routes for the CRUD operations in routes/web.php:

Route::post('/post', [PostController::class, 'create']);
Route::get('/post/{id}', [PostController::class, 'read']);
Route::put('/post/{id}', [PostController::class, 'update']);
Route::delete('/post/{id}', [PostController::class, 'delete']);

Conclusion:

By leveraging the features of Laravel and MongoDB, you can build flexible and scalable web applications. For any queries or doubts, share it with me through the comment box. Share the tutorial with your friends to help them learn about integrating MongoDB with Laravel.

Happy Coding!

Click to rate this post!
[Total: 0 Average: 0]
Bharat Desai

Bharat Desai is a Co-Founder at MageComp. He is an Adobe Magento Certified Frontend Developer ? with having 8+ Years of experience and has developed 150+ Magento 2 Products with MageComp. He has an unquenchable thirst to learn new things. On off days you can find him playing the game of Chess ♟️ or Cricket ?.

Recent Posts

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

1 day ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

3 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

5 days ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

6 days ago

Best Beginners Guide to Shopify Balance Account

If you are a Shopify admin, using a Shopify Balance Account for your business revenue…

6 days ago

8 Best Social Login Apps for Shopify Store in 2024

Running an eCommerce business can be incredibly demanding, leaving entrepreneurs little time to focus on…

6 days ago