Copied!
Laravel

How to Integrate MongoDB with Laravel and Build a Full CRUD Application

mongodb-crud-with-laravel
Shahroz Javed
Jun 09, 2025 . 58 views

Table Of Contents

 

Introduction

MongoDB is a powerful NoSQL database that pairs well with modern applications that need flexibility and scalability. Laravel, a PHP framework known for its elegance and developer-friendliness, now officially supports MongoDB with the mongodb/laravel-mongodb driver. In this guide, we’ll build a complete CRUD application using Laravel and MongoDB step-by-step.

Install MongoDB Driver in Laravel

composer require mongodb/laravel-mongodb

Also make sure you have the MongoDB PHP extension installed.

Environment Configuration

In your .env file, set the MongoDB credentials:

DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
DB_PORT=27017
DB_DATABASE=mongo_db
DB_USERNAME=mongo_user
DB_PASSWORD=mongo_pass

Configure MongoDB in config/database.php

'mongodb' => [
  'driver' => 'mongodb',
  'host' => env('DB_HOST'),
  'port' => env('DB_PORT'),
  'database' => env('DB_DATABASE'),
  'username' => env('DB_USERNAME'),
  'password' => env('DB_PASSWORD'),
  'options' => [
    'database' => 'admin', // Authentication DB
  ],
],

Create Product Model

use MongoDB\Laravel\Eloquent\Model;

class Product extends Model
{
    protected $connection = 'mongodb';
    protected $collection = 'products';

    protected $fillable = ['name', 'price', 'description'];
}

Create Product Controller

php artisan make:controller ProductController --resource

ProductController.php

public function index() {
    $products = Product::latest()->paginate(10);
    return view('products.index', compact('products'));
}

public function create() {
    return view('products.create');
}

public function store(Request $request) {
    Product::create($request->validate([
        'name' => 'required|string',
        'price' => 'required|numeric',
        'description' => 'nullable|string',
    ]));

    return redirect()->route('products.index')->with('success', 'Product created successfully!');
}

public function edit(Product $product) {
    return view('products.edit', compact('product'));
}

public function update(Request $request, Product $product) {
    $product->update($request->validate([
        'name' => 'required|string',
        'price' => 'required|numeric',
        'description' => 'nullable|string',
    ]));

    return redirect()->route('products.index')->with('success', 'Product updated!');
}

public function destroy(Product $product) {
    $product->delete();
    return redirect()->route('products.index')->with('success', 'Product deleted!');
}

Setup Blade Layout

resources/views/app.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>MongoDB CRUD in Laravel</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-4">
  <div class="container">
    @yield('content')
  </div>
</body>
</html>

Views

products/index.blade.php

@extends('app')
@section('content')
<h2>Product List</h2>

<a class="btn btn-primary mb-3" href="{{ route('products.create') }}">Add Product</a>

@if(session('success'))
    <div class="alert alert-success">{{ session('success') }}</div>
@endif

<table class="table table-bordered">
    <thead><tr><th>#</th><th>Name</th><th>Price</th><th>Description</th><th>Actions</th></tr></thead>
    <tbody>
    @forelse($products as $product)
        <tr>
            <td>{{ $loop->iteration }}</td>
            <td>{{ $product->name }}</td>
            <td>{{ $product->price }}</td>
            <td>{{ $product->description }}</td>
            <td>
                <a href="{{ route('products.edit', $product) }}" class="btn btn-warning btn-sm">Edit</a>
                <form method="POST" action="{{ route('products.destroy', $product) }}" style="display:inline-block">
                    @csrf @method('DELETE')
                    <button onclick="return confirm('Are you sure?')" class="btn btn-danger btn-sm">Delete</button>
                </form>
            </td>
        </tr>
    @empty
        <tr><td colspan="5">No products found.</td></tr>
    @endforelse
    </tbody>
</table>

{{ $products->links() }}
@endsection

products/create.blade.php

@extends('app')
@section('content')
<h2>Add Product</h2>

<form action="{{ route('products.store') }}" method="POST">
    @csrf
    <div class="mb-3">
        <label>Name</label>
        <input name="name" class="form-control" required>
    </div>

    <div class="mb-3">
        <label>Price</label>
        <input name="price" type="number" class="form-control" required>
    </div>

    <div class="mb-3">
        <label>Description</label>
        <textarea name="description" class="form-control"></textarea>
    </div>

    <button class="btn btn-success">Save</button>
    <a href="{{ route('products.index') }}" class="btn btn-secondary">Cancel</a>
</form>
@endsection

products/edit.blade.php

@extends('app')
@section('content')
<h2>Edit Product</h2>

<form action="{{ route('products.update', $product) }}" method="POST">
    @csrf @method('PUT')
    <div class="mb-3">
        <label>Name</label>
        <input name="name" value="{{ $product->name }}" class="form-control" required>
    </div>

    <div class="mb-3">
        <label>Price</label>
        <input name="price" value="{{ $product->price }}" type="number" class="form-control" required>
    </div>

    <div class="mb-3">
        <label>Description</label>
        <textarea name="description" class="form-control">{{ $product->description }}</textarea>
    </div>

    <button class="btn btn-success">Update</button>
    <a href="{{ route('products.index') }}" class="btn btn-secondary">Cancel</a>
</form>
@endsection

Conclusion

By integrating MongoDB with Laravel, you unlock the power of flexible NoSQL data handling in a developer-friendly environment. This tutorial helped you connect Laravel with MongoDB, configure everything, and build a full-featured CRUD app. Whether you're scaling an existing Laravel project or exploring NoSQL, MongoDB offers powerful capabilities that pair well with Laravel’s ecosystem.

17 Shares

Similar Posts