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" --tag="mongodb-config"
    

    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 = 'mongodb';
        protected $collection = 'users';
        protected $fillable = ['name', 'email'];
    }
    
  3. First Query:

    $users = User::where('email', 'like', '%@gmail.com')->get();
    

Key First Use Cases

  • CRUD Operations: Use Eloquent methods like create(), find(), update(), delete().
  • Aggregation: Leverage MongoDB’s aggregation pipeline:
    $result = User::aggregate([
        ['$match' => ['age' => ['$gt' => 25]]],
        ['$group' => ['_id' => '$country', 'count' => ['$sum' => 1]]]
    ])->toArray();
    
  • Index Management: Create indexes via migrations or Artisan:
    php artisan mongodb:create-index users email --unique
    

Implementation Patterns

Core Workflows

1. Model Design

  • Schema Flexibility: Use $casts for type conversion (e.g., DateTime, Array) and $appends for computed fields:
    protected $casts = [
        'created_at' => 'date',
        'metadata' => 'array',
    ];
    protected $appends = ['full_name'];
    
  • Embedded Documents: Define nested models with hasOne, hasMany, or embedOne/embedMany:
    class Profile extends Model
    {
        public function user()
        {
            return $this->belongsTo(User::class);
        }
    }
    

2. Query Building

  • Hybrid Queries: Combine Eloquent and MongoDB query builder methods:
    $query = User::where('status', 'active')
        ->whereIn('role', ['admin', 'editor'])
        ->orderBy('name', 'asc')
        ->limit(10);
    
  • Text Search: Use MongoDB’s $text operator:
    $results = User::where('name', 'text', 'John Doe')->get();
    
  • Geospatial Queries: Leverage MongoDB’s geojson support:
    $near = [
        '$near' => [
            '$geometry' => ['type' => 'Point', 'coordinates' => [-73.9667, 40.78]],
            '$maxDistance' => 1000,
        ],
    ];
    $users = User::where('location', $near)->get();
    

3. Relationships

  • Polymorphic Relations: Use morphTo/morphWith:
    class Comment extends Model
    {
        public function commentable()
        {
            return $this->morphTo();
        }
    }
    
  • Custom Accessors/Mutators: Override getAttribute() or use $accessors:
    public function getFullNameAttribute()
    {
        return "{$this->first_name} {$this->last_name}";
    }
    

4. Transactions

  • ACID Compliance: Use Laravel’s transaction manager:
    DB::transaction(function () {
        User::create(['name' => 'John']);
        Profile::create(['user_id' => $user->id]);
    });
    
  • Retry Logic: Handle deadlocks with DB::retry():
    DB::retry(function () {
        // Transaction logic
    }, 3);
    

5. Migrations & Schema

  • Schema Validation: Define validation rules in migrations:
    Schema::create('users', function (Blueprint $collection) {
        $collection->index('email', ['unique' => true]);
        $collection->index('created_at');
        $collection->validator(function ($validator) {
            $validator->required('email')->email();
        });
    });
    
  • TTL Indexes: Automate document expiration:
    Schema::create('sessions', function (Blueprint $collection) {
        $collection->index('expires_at', ['expireAfterSeconds' => 0]);
    });
    

6. Performance Optimization

  • Projection: Fetch only needed fields:
    $users = User::select(['name', 'email'])->get();
    
  • Cursor Pagination: Use simplePaginate() or cursor() for large datasets:
    $users = User::cursor()->paginate(20);
    
  • Batch Processing: Use chunk() for memory efficiency:
    User::chunk(100, function ($users) {
        foreach ($users as $user) {
            // Process each user
        }
    });
    

Integration Tips

Laravel Ecosystem

  • Scout: Use MongoDB for full-text search:
    use MongoDB\Laravel\Scout\MongoScoutEngine;
    
    class User extends Model
    {
        public function shouldBeSearchable()
        {
            return true;
        }
    }
    
  • Queues: Store jobs in MongoDB:
    Queue::later(now()->addMinutes(5), new SendEmailJob($user));
    
  • Caching: Use MongoDB as a cache store (via mongodb session driver):
    Cache::put('key', 'value', now()->addHours(1));
    

Testing

  • Mocking: Use MongoDB\Laravel\Testing\CreatesApplication:
    use MongoDB\Laravel\Testing\CreatesApplication;
    
    class UserTest extends TestCase
    {
        use CreatesApplication;
    
        public function test_create_user()
        {
            $user = User::create(['name' => 'Test']);
            $this->assertEquals('Test', $user->name);
        }
    }
    
  • Database Transactions: Wrap tests in transactions:
    public function test_with_transaction()
    {
        $this->withoutExceptionHandling();
        DB::beginTransaction();
    
        try {
            // Test logic
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            $this->fail($e->getMessage());
        }
    }
    

Deployment

  • Connection Pooling: Configure in .env:
    MONGODB_POOL_SIZE=50
    MONGODB_POOL_TIMEOUT=30
    
  • Read Preference: Route reads to secondary nodes:
    $users = User::connection('mongodb')->readPreference('secondary')->get();
    
  • Retryable Writes: Enable in config:
    'retry_writes' => true,
    'retry_writes_max_attempts' => 3,
    

Gotchas and Tips

Pitfalls

1. Schema Mismatches

  • Issue: MongoDB is schema-less, but Laravel’s $fillable/$guarded still enforce write rules.
    • Fix: Ensure $fillable matches your application’s write requirements. Use $casts for type safety.
    // Avoid:
    $user = User::create(['invalid_field' => 'value']); // Throws MassAssignmentException
    
    // Prefer:
    $user = User::create(['name' => 'John']); // Valid
    

2. ID Handling

  • Issue: MongoDB uses _id (ObjectId), but Laravel may alias it to id. Conflicts arise in queries or serializers.
    • Fix: Explicitly define $primaryKey and $keyType:
    class User extends Model
    {
        protected $primaryKey = '_id';
        protected $keyType = 'string'; // or 'object' for ObjectId
    }
    
    • Gotcha: Avoid using id in queries unless aliased:
    // Works:
    User::where('_id', $objectId)->first();
    
    // May fail if not aliased:
    User::where('id', $objectId)->first();
    

3. Soft Deletes

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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai