How to Integrate and Use MongoDB with 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!

Previous Article

NodeJS | Callback Function

Next Article

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨