Laravel, a popular PHP framework, provides seamless integration with various databases, including MongoDB—a NoSQL document-oriented database. With Laravel 10, integrating MongoDB into your Laravel applications has become even more straightforward. In this post, we will walk through the process of setting up MongoDB in Laravel 10 and provide practical examples to help you get started.
Section 1: Setting Up MongoDB in Laravel 10
Install Required Packages:
jenssegers/mongodb
package, which provides the MongoDB integration for Laravel. Run the following command in your Laravel project directory:composer require jenssegers/mongodb
Configure Database Connection:
config/database.php
file in your Laravel project and update the connections
array.
Section 2: Working with MongoDB in Laravel 10
Create MongoDB Models:
Jenssegers\Mongodb\Eloquent\Model
instead of Laravel's base Model
class.collection
property.<?php
namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model;
class Product extends Model
{
protected $collection = 'products';
// Define relationships, accessors, mutators, etc.
}
Perform CRUD Operations:
$product = new Product;
$product->name = 'Sample Product';
$product->price = 19.99;
$product->save();
$product = Product::find($id);
$product = Product::find($id);
$product->price = 24.99;
$product->save();
$product = Product::find($id);
$product->delete();
Querying MongoDB Data:
$products = Product::where('price', '>', 10)->get();
$products = Product::where('price', '>', 10)
->orWhere('category', 'Electronics')
->get();
Section 3: Advanced MongoDB Features in Laravel 10
Aggregations:
Geospatial Queries: