## Getting Started
### Minimal Setup
1. **Installation**:
```bash
composer require mongodb/laravel-mongodb
Add to config/app.php under providers:
MongoDB\Laravel\MongoDBServiceProvider::class,
Configuration: Publish the config file:
php artisan vendor:publish --provider="MongoDB\Laravel\MongoDBServiceProvider"
Update .env with your MongoDB connection string:
MONGODB_CONNECTION=default
MONGODB_DATABASE=your_database
MONGODB_URI=mongodb://username:password@host:port/database
First Model:
Extend MongoDB\Eloquent\Model in app/Models:
use MongoDB\Eloquent\Model;
class User extends Model
{
protected $connection = 'default';
protected $collection = 'users';
protected $fillable = ['name', 'email'];
}
First Query:
$users = User::where('email', 'like', '%@example.com')->get();
create(), find(), update(), delete() just like Eloquent.$result = User::aggregate([
['$match' => ['age' => ['$gt' => 18]]],
['$group' => ['_id' => '$country', 'count' => ['$sum' => 1]]]
]);
php artisan mongodb:create-index users email_text --unique
$casts for automatic type conversion (e.g., DateTime, Array):
protected $casts = [
'created_at' => 'date',
'metadata' => 'array',
];
$embedded:
class Profile extends Model
{
protected $embedded = true;
}
class User extends Model
{
public function profile()
{
return $this->embedsOne(Profile::class);
}
}
$query = User::query()
->where('status', 'active')
->whereIn('role', ['admin', 'editor'])
->orderBy('name', 'asc')
->limit(10);
$results = User::textSearch('email', 'john')->get();
Ensure a text index exists:
php artisan mongodb:create-index users email_text --type text
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
DB::transaction() for multi-document operations:
DB::transaction(function () {
User::create(['name' => 'John']);
Profile::create(['user_id' => $user->id, 'bio' => 'Developer']);
});
app/Providers/EventServiceProvider:
protected $observers = [
User::class => UserObserver::class,
];
class UserObserver
{
public function saving(User $user)
{
if (empty($user->email)) {
$user->email = $user->name . '@example.com';
}
}
}
composer require mongodb/laravel-scout
Configure in config/scout.php:
'driver' => 'mongodb',
QUEUE_CONNECTION=mongodb
SESSION_DRIVER=mongodb
$users = User::orderBy('created_at')->paginate(20);
chunk() for large updates:
User::where('status', 'inactive')->chunk(100, function ($users) {
foreach ($users as $user) {
$user->update(['status' => 'active']);
}
});
MongoDB\Database\Client for in-memory testing:
use MongoDB\Database\Client;
$client = new Client('mongodb://localhost:27017', [
'connect' => false,
'directConnection' => true,
]);
MongoDB\Laravel\Testing\CreatesCollections:
use MongoDB\Laravel\Testing\CreatesCollections;
class UserTest extends TestCase
{
use CreatesCollections;
public function test_user_creation()
{
$user = User::create(['name' => 'Test']);
$this->assertDatabaseHas('users', ['name' => 'Test']);
}
}
_id vs id:
_id by default, but the package aliases it to id for Eloquent compatibility.$primaryKey = '_id' in your model if you prefer _id explicitly.Soft Deletes:
SoftDeletes trait is deprecated. Use deleted_at with custom queries:
User::whereNull('deleted_at')->get();
Hybrid Queries:
$lookup in aggregation instead:
User::aggregate([
['$lookup' => [
'from' => 'profiles',
'localField' => '_id',
'foreignField' => 'user_id',
'as' => 'profile'
]]
]);
Transactions:
DB::transaction() with a retry wrapper:
$attempts = 3;
while ($attempts--) {
try {
DB::transaction(...);
break;
} catch (Exception $e) {
if ($attempts === 0) throw $e;
sleep(1);
}
}
Schema Validation:
$schema in your model:
protected $schema = [
'bsonType' => 'object',
'required' => ['name', 'email'],
'properties' => [
'name' => ['bsonType' => 'string'],
'email' => ['bsonType' => 'string', 'pattern' => '^.+@.+$']
]
];
php artisan mongodb:validate-schema users
Query Logging:
Enable debug mode in .env:
MONGODB_DEBUG=true
Logs will show executed queries in storage/logs/laravel.log.
Explain Plans:
Use explain() to analyze query performance:
$explanation = User::where('age', '>', 18)->explain();
dd($explanation);
Connection Issues:
MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/db?retryWrites=true&w=majority&ssl=true
mongodb://localhost:27017.Index Optimization:
php artisan mongodb:show-indexes users to inspect indexes.php artisan mongodb:drop-index users email_text
How can I help you explore Laravel packages today?