Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Mongodb Laravel Package

mongodb/laravel-mongodb

MongoDB integration for Laravel Eloquent and query builder. Extends core Laravel classes to use the same familiar API with MongoDB. Official mongodb/laravel-mongodb package, compatible with Laravel 10.x; docs and releases maintained by MongoDB.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require mongodb/laravel-mongodb

Add to config/app.php under providers:

MongoDB\Laravel\MongoDBServiceProvider::class,
  1. 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
    
  2. First Model: Extend MongoDB\Laravel\Eloquent\Model instead of Illuminate\Database\Eloquent\Model:

    use MongoDB\Laravel\Eloquent\Model;
    
    class User extends Model
    {
        protected $connection = 'default';
        protected $collection = 'users';
        protected $fillable = ['name', 'email'];
    }
    
  3. First Query:

    $users = User::where('name', 'John')->get();
    $user = User::find('507f1f77bcf86cd799439011');
    

Key First Use Cases

  • CRUD Operations: Use Eloquent methods (create(), update(), delete()) as usual.
  • Aggregation: Leverage MongoDB’s aggregation pipeline:
    $result = User::aggregate([
        ['$match' => ['age' => ['$gt' => 25]]],
        ['$group' => ['_id' => '$department', 'count' => ['$sum' => 1]]]
    ]);
    
  • Schema Validation: Define schema rules in schema() method:
    public static function schema()
    {
        return [
            'bsonType' => 'object',
            'properties' => [
                'name' => ['bsonType' => 'string'],
                'email' => ['bsonType' => 'string', 'pattern' => '^.+@.+\\..+$']
            ],
            'required' => ['name', 'email']
        ];
    }
    

Implementation Patterns

Core Workflows

1. Model Design

  • Collections vs. Tables: Use protected $collection to define the MongoDB collection name.
  • Embedded Documents: Define relationships using $ref or embed directly:
    class Address extends Model
    {
        protected $collection = 'addresses';
    }
    
    class User extends Model
    {
        public function address()
        {
            return $this->embedOne('address');
        }
    }
    
  • Indexing: Define indexes in up() method of migrations:
    Schema::create('users', function (Blueprint $collection) {
        $collection->index('email', ['unique' => true]);
        $collection->index(['name', 'created_at']);
    });
    

2. Query Building

  • Hybrid Queries: Combine Eloquent and MongoDB Query Builder:
    $query = User::query()
        ->where('name', 'John')
        ->where('age', '>', 30)
        ->orderBy('created_at', 'desc')
        ->limit(10);
    
  • Aggregation Pipeline: Use aggregate() for complex operations:
    $pipeline = [
        ['$match' => ['status' => 'active']],
        ['$lookup' => [
            'from' => 'orders',
            'localField' => '_id',
            'foreignField' => 'user_id',
            'as' => 'orders'
        ]]
    ];
    $result = User::aggregate($pipeline);
    
  • Text Search: Use $text operator:
    $users = User::where('name', ['$text' => ['$search' => 'John']])->get();
    

3. Transactions

  • Multi-Document Transactions: Use DB::transaction():
    DB::transaction(function () {
        User::create(['name' => 'Alice']);
        Order::create(['user_id' => $user->id, 'amount' => 100]);
    });
    
  • Retry Logic: Handle transient errors with retries:
    DB::transaction(function () use (&$retries) {
        try {
            // Transaction logic
        } catch (MongoDB\Driver\Exception\RuntimeException $e) {
            if ($retries++ < 3) {
                return $this->transaction($callback);
            }
            throw $e;
        }
    });
    

4. Relationships

  • Embedded Relationships:
    class User extends Model
    {
        public function addresses()
        {
            return $this->embedMany('address');
        }
    }
    
  • Referenced Relationships:
    class User extends Model
    {
        public function orders()
        {
            return $this->hasMany(Order::class);
        }
    }
    
  • Polymorphic Relationships:
    class Comment extends Model
    {
        public function commentable()
        {
            return $this->morphTo();
        }
    }
    

5. Events and Observers

  • Model Events: Use observables() in boot():
    protected static function boot()
    {
        parent::boot();
        static::observables(['created', 'updated']);
    }
    
  • Custom Observers:
    class UserObserver
    {
        public function creating(User $user)
        {
            $user->uuid = Str::uuid()->toString();
        }
    }
    
    Register in AppServiceProvider:
    User::observe(UserObserver::class);
    

6. Migrations and Schema

  • Schema Changes: Use Schema facade:
    Schema::create('users', function (Blueprint $collection) {
        $collection->index('email', ['unique' => true, 'sparse' => true]);
        $collection->index('created_at', ['expireAfterSeconds' => 2592000]); // TTL index
    });
    
  • Views: Create views for read-optimized queries:
    Schema::createView('user_view', ['viewOn' => 'users'], function (Blueprint $view) {
        $view->viewDefinition([
            ['$match' => ['status' => 'active']],
            ['$project' => ['name' => 1, 'email' => 1]]
        ]);
    });
    

7. Scout Integration

  • Full-Text Search: Use Laravel Scout with MongoDB:
    class User extends Model
    {
        public function shouldBeSearchable()
        {
            return $this->isActive();
        }
    
        public function toSearchableArray()
        {
            return ['name' => $this->name, 'email' => $this->email];
        }
    }
    
    Configure in config/scout.php:
    'driver' => 'mongodb',
    

Gotchas and Tips

Common Pitfalls

  1. ID Handling:

    • MongoDB uses _id (ObjectId) by default, not auto-incrementing integers.
    • Avoid assuming IDs are sequential or numeric. Use Str::uuid() or ObjectId for custom IDs:
      use MongoDB\BSON\ObjectId;
      
      $id = new ObjectId();
      
    • Gotcha: If you override $primaryKey, ensure it’s castable to/from BSON:
      protected $primaryKey = 'uuid';
      protected $keyType = 'string';
      
  2. Soft Deletes:

    • The package deprecated MongoSoftDeletes trait in favor of native MongoDB isDeleted field.
    • Migration: Update models to use:
      use MongoDB\Laravel\Eloquent\SoftDeletes;
      
      class User extends Model
      {
          use SoftDeletes;
          protected $dates = ['deleted_at'];
      }
      
    • Query Gotcha: Soft-deleted models are excluded by default. Use withTrashed() to include them:
      User::withTrashed()->get();
      
  3. Schema Validation:

    • Schema validation runs on save() and update(). Invalid data throws MongoDB\Driver\Exception\InvalidArgumentException.
    • Tip: Validate in prepareForValidation() to catch issues early:
      protected function prepareForValidation()
      {
          if (empty($this->email)) {
              throw new \InvalidArgumentException('Email is required.');
          }
      }
      
  4. Aggregation Quirks:

    • Stage Order: Aggregation stages execute in order. Place $match early to reduce documents processed.
    • Memory Limits: Large aggregations may hit MongoDB’s 100MB memory limit. Use $allowDiskUse:
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport