Installation:
composer require mongodb/laravel-mongodb
Add the service provider to config/app.php:
'providers' => [
// ...
MongoDB\Laravel\MongoDBServiceProvider::class,
],
Configure .env:
DB_CONNECTION=mongodb
DB_HOST=127.0.0.1
DB_PORT=27017
DB_DATABASE=your_db_name
First Model:
use MongoDB\Eloquent\Model;
class User extends Model
{
protected $connection = 'mongodb';
protected $collection = 'users';
protected $fillable = ['name', 'email'];
}
First Query:
$users = User::where('email', 'user@example.com')->get();
php artisan vendor:publish --provider="MongoDB\Laravel\MongoDBServiceProvider" --tag=migrationsModel Definitions:
protected $collection to specify the MongoDB collection.protected $fillable/$guarded for mass assignment (same as Eloquent).class Product extends Model
{
protected $collection = 'products';
protected $fillable = ['name', 'price', 'tags'];
}
Querying:
Product::where('price', '<', 100)->get();
Product::aggregate([
['$match' => ['price' => ['$gt' => 50]]],
['$group' => ['_id' => '$category', 'avg' => ['$avg' => '$price']]]
])->toArray();
Product::where('name', 'text', 'laptop')->get();
Relationships:
class Order extends Model
{
public function items()
{
return $this->hasMany(OrderItem::class);
}
}
class User extends Model
{
protected $embeds = ['address'];
protected $embedsOne = ['profile'];
}
Events & Observers:
observables() and dispatchesEvents() (same as Eloquent).class User extends Model
{
public static function boot()
{
parent::boot();
static::created(function ($user) {
Log::info("New user created: {$user->email}");
});
}
}
Transactions:
DB::transaction() for multi-document operations:
DB::transaction(function () {
User::create(['name' => 'John']);
Product::create(['name' => 'Laptop']);
});
class HybridModel extends Model
{
protected $connection = 'mysql'; // Defaults to SQL
}
class Product extends Model
{
public function toSearchableArray()
{
return ['name' => $this->name, 'description' => $this->description];
}
}
php artisan make:resource ProductResource
Schema Differences:
FormRequest or custom validation rules).use Illuminate\Support\Facades\Validator;
$validator = Validator::make($data, [
'email' => 'required|email',
'age' => 'integer|min:18',
]);
Indexing:
Schema::connection('mongodb')->create('users', function (Blueprint $collection) {
$collection->index('email', 'unique');
$collection->index('name');
});
email, created_at).Relationships:
$embeds) require explicit handling:
$user = User::find(1);
$user->address->push(['city' => 'New York']); // Update embedded doc
$user->save();
$references) behave like SQL joins but may impact performance.Pagination:
cursor() for large datasets to avoid memory issues:
$cursor = Product::where('price', '>', 100)->cursor();
foreach ($cursor as $product) {
// Process one item at a time
}
Atomic Operators:
$inc, $push, etc., require explicit syntax:
User::where('email', 'user@example.com')
->update(['$inc' => ['age' => 1]]); // Increment age by 1
Query Logging:
Enable debug mode in .env:
MONGO_DEBUG=true
Logs will appear in storage/logs/laravel.log.
Raw Queries:
Use toMongo() to inspect raw queries:
$query = User::where('name', 'John')->getQuery();
dd($query->toMongo());
Connection Issues:
.env credentials and MongoDB server status.DB::connection('mongodb')->getMongoClient()->selectDatabase('your_db')->command(['ping' => 1]);
Custom Operators: Extend the query builder with custom MongoDB operators:
use MongoDB\Eloquent\Builder;
Builder::macro('customOperator', function ($field, $operator) {
return $this->where($field, $operator);
});
Usage:
User::customOperator('age', ['$gt' => 25])->get();
Model Events:
Override boot() for custom logic:
class User extends Model
{
public static function boot()
{
parent::boot();
static::retrieved(function ($user) {
if (!$user->profile) {
$user->profile = new stdClass(); // Initialize embedded doc
}
});
}
}
Query Scopes: Add reusable query logic:
class User extends Model
{
public function scopeActive($query)
{
return $query->where('status', 'active');
}
}
Usage:
User::active()->get();
Middleware: Use Laravel middleware to modify MongoDB queries:
class LogMongoQueries
{
public function handle($request, Closure $next)
{
if (app()->bound('mongodb')) {
\Log::info('MongoDB query executed');
}
return $next($request);
}
}
How can I help you explore Laravel packages today?