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 the Query Builder, extending the native Laravel API to work with MongoDB. Official mongodb/laravel-mongodb package (formerly jenssegers), compatible with Laravel 10.x.

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 MongoDB connection details:

    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 = 'mongodb';
        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 create(), find(), update(), delete() just like Eloquent.
  • Aggregation: Leverage MongoDB’s native aggregation pipeline:
    $result = User::aggregate([
        ['$match' => ['age' => ['$gt' => 25]]],
        ['$group' => ['_id' => '$department', 'count' => ['$sum' => 1]]]
    ])->toArray();
    
  • Index Management: Define indexes in migrations:
    Schema::create('users', function (Blueprint $collection) {
        $collection->index('email', ['unique' => true]);
        $collection->index('created_at');
    });
    

Implementation Patterns

Core Workflows

1. Modeling and Schema Design

  • Embedded Documents: Use $embedOne and $embedMany for nested structures:
    class Profile extends Model
    {
        public function user()
        {
            return $this->embedOne('user');
        }
    }
    
  • References: Use $referenceOne and $referenceMany for relationships:
    class Post extends Model
    {
        public function author()
        {
            return $this->referenceOne('User', 'author_id');
        }
    }
    
  • Schema Validation: Define validation rules in the model:
    class User extends Model
    {
        protected $schema = [
            'bsonType' => 'object',
            'required' => ['name', 'email'],
            'properties' => [
                'name' => ['bsonType' => 'string'],
                'email' => ['bsonType' => 'string', 'pattern' => '^[^@]+@[^@]+\.[^@]+$']
            ]
        ];
    }
    

2. Query Building

  • Hybrid Queries: Combine Eloquent and MongoDB queries:
    $query = User::where('active', true)
                ->where('age', '>', 25)
                ->orderBy('name', 'asc')
                ->limit(10);
    
  • Aggregation Pipelines: Use $match, $group, $project, etc.:
    $pipeline = [
        ['$match' => ['status' => 'active']],
        ['$group' => ['_id' => '$category', 'total' => ['$sum' => 1]]],
        ['$sort' => ['total' => -1]]
    ];
    $result = User::aggregate($pipeline)->toArray();
    
  • Text Search: Utilize MongoDB’s text indexes:
    Schema::create('articles', function (Blueprint $collection) {
        $collection->text('title', 'content');
    });
    $results = Article::whereText('title', 'laravel')->get();
    

3. Relationships

  • One-to-Many:
    class Post extends Model
    {
        public function comments()
        {
            return $this->hasMany(Comment::class);
        }
    }
    
  • Many-to-Many:
    class User extends Model
    {
        public function roles()
        {
            return $this->belongsToMany(Role::class);
        }
    }
    
  • Polymorphic:
    class Comment extends Model
    {
        public function commentable()
        {
            return $this->morphTo();
        }
    }
    

4. Transactions

  • Use DB::transaction() for atomic operations:
    DB::transaction(function () {
        $user = User::find($id);
        $user->update(['balance' => $user->balance - $amount]);
        $transaction = Transaction::create(['user_id' => $id, 'amount' => $amount]);
    });
    

5. Events and Observers

  • Listen to model events:
    class UserObserver
    {
        public function creating(User $user)
        {
            $user->uuid = Str::uuid()->toString();
        }
    }
    
    Register in AppServiceProvider:
    User::observe(UserObserver::class);
    

6. Migrations and Schema

  • Create collections with indexes:
    Schema::create('users', function (Blueprint $collection) {
        $collection->index('email', ['unique' => true, 'sparse' => true]);
        $collection->index('last_login', ['expireAfterSeconds' => 2592000]); // TTL index
    });
    

Integration Tips

  1. Laravel Scout: Use MongoDB for full-text search:

    class User extends Model implements Scoutable
    {
        public function toSearchableArray()
        {
            return ['name' => $this->name, 'email' => $this->email];
        }
    }
    

    Configure in config/scout.php:

    'driver' => 'mongodb',
    
  2. Queues: Store jobs in MongoDB:

    QUEUE_CONNECTION=mongodb
    

    Use MongoQueue for job storage.

  3. Caching: Use MongoDB as a cache driver:

    CACHE_DRIVER=mongodb
    
  4. API Resources: Transform MongoDB models to JSON:

    class UserResource extends JsonResource
    {
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'name' => $this->name,
                'email' => $this->email,
                'created_at' => $this->created_at->toDateTimeString(),
            ];
        }
    }
    
  5. Testing: Use MongoDbTestCase for database testing:

    use MongoDB\Laravel\Testing\MongoDbTestCase;
    
    class UserTest extends MongoDbTestCase
    {
        public function test_create_user()
        {
            $user = User::create(['name' => 'John', 'email' => 'john@example.com']);
            $this->assertEquals('John', $user->name);
        }
    }
    

Gotchas and Tips

Pitfalls and Debugging

  1. ID Handling:

    • MongoDB uses _id (ObjectId by default), not id. Avoid aliasing _id to id in embedded documents (use $id instead).
    • When inserting, ensure _id is not manually set unless using a custom ID strategy:
      $user = new User(['name' => 'John']);
      $user->save(); // Auto-generates _id
      
  2. Soft Deletes:

    • The SoftDeletes trait is deprecated in favor of MongoDB’s native deleted_at field. Use:
      use MongoDB\Laravel\Eloquent\SoftDeletes;
      
      class User extends Model
      {
          use SoftDeletes;
          protected $dates = ['deleted_at'];
      }
      
    • Restore with:
      $user->restore();
      
  3. Transactions:

    • MongoDB transactions require a replica set or sharded cluster. Single-node deployments won’t support transactions.
    • Use DB::transaction() with caution; nested transactions are not supported.
  4. Schema Validation:

    • Schema validation is enforced at the database level. Test validation rules thoroughly:
      try {
          User::create(['name' => 123]); // Will fail validation
      } catch (MongoDB\Driver\Exception\InvalidArgumentException $e) {
          // Handle validation error
      }
      
  5. Hybrid Queries:

    • Avoid mixing Eloquent and MongoDB queries when possible
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony