Laravel: MongoDB CRUD in Laravel
Introduction
This tutorial guides you through performing CRUD (Create, Read, Update, Delete) operations with MongoDB in a Laravel application. MongoDB is a NoSQL database, and using it with Laravel involves the Eloquent ORM and the jenssegers/mongodb
package.
MongoDB CRUD in Laravel
Syntax
Make sure to install the jenssegers/mongodb
package via Composer:
composer require jenssegers/mongodb
Then, configure the package and use the Eloquent model for MongoDB:
// Sample Eloquent model for MongoDB
namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Product extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'products';
protected $fillable = ['name', 'price'];
}
Example
Consider a simple Laravel controller with MongoDB CRUD operations:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
class ProductController extends Controller
{
public function index()
{
$products = Product::all();
return view('products.index', compact('products'));
}
public function create()
{
return view('products.create');
}
public function store(Request $request)
{
Product::create($request->all());
return redirect()->route('products.index');
}
public function edit($id)
{
$product = Product::find($id);
return view('products.edit', compact('product'));
}
public function update(Request $request, $id)
{
$product = Product::find($id);
$product->update($request->all());
return redirect()->route('products.index');
}
public function destroy($id)
{
Product::find($id)->delete();
return redirect()->route('products.index');
}
}
Output
The controller actions handle creating, reading, updating, and deleting products in the MongoDB collection.
Explanation
In this example, the ProductController
demonstrates typical CRUD operations for a MongoDB collection using Laravel and the jenssegers/mongodb
package. The Eloquent model Product
represents the MongoDB document structure.
Use
- MongoDB Integration: Utilize MongoDB as the database for your Laravel application.
- NoSQL Flexibility: Leverage the flexibility of NoSQL databases for certain types of data.
- Eloquent ORM: Continue using the Eloquent ORM for MongoDB just like you would for a traditional relational database.
Important Points
- Install the
jenssegers/mongodb
package to integrate MongoDB with Laravel. - Configure the MongoDB connection in Laravel's
config/database.php
. - Use the Eloquent model for MongoDB to interact with the database.
Summary
Integrating MongoDB with Laravel allows you to take advantage of the features of a NoSQL database in your web application. Whether you're working with flexible data structures or need horizontal scalability, Laravel and MongoDB together provide a powerful combination for modern web development.