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

Mongodb Migrations Laravel Package

antimattr/mongodb-migrations

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require antimattr/mongodb-migrations
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Antimattr\MongoDBMigrations\MongoDBMigrationsServiceProvider::class,
    ],
    
  2. Publish Configuration

    php artisan vendor:publish --provider="Antimattr\MongoDBMigrations\MongoDBMigrationsServiceProvider" --tag="config"
    

    Edit config/mongodb-migrations.php to match your MongoDB connection (e.g., mongodb in config/database.php).

  3. First Migration Create a migration file:

    php artisan make:migration create_users_collection --collection=users
    

    Define schema in database/migrations/[timestamp]_create_users_collection.php:

    use Antimattr\MongoDBMigrations\Migration;
    use Antimattr\MongoDBMigrations\Schema\Collection;
    
    class CreateUsersCollection extends Migration
    {
        public function up()
        {
            Collection::create('users', function ($collection) {
                $collection->index('email', ['unique' => true]);
                $collection->index('created_at');
            });
        }
    
        public function down()
        {
            Collection::drop('users');
        }
    }
    
  4. Run Migrations

    php artisan mongodb:migrate
    

First Use Case: Schema Changes

  • Add a Field: Extend the up() method to modify the schema:
    $collection->field('status', ['type' => 'string', 'default' => 'active']);
    
  • Run:
    php artisan mongodb:migrate
    

Implementation Patterns

Workflow Integration

  1. Version Control

    • Store migrations in database/migrations/ alongside Eloquent migrations.
    • Use php artisan mongodb:migrate --step=1 for incremental testing.
  2. Seeding Data Combine with laravel/breeze or seeds:

    public function up()
    {
        Collection::create('users', function ($collection) {
            // Schema...
        });
    
        // Seed after creation
        DB::collection('users')->insert([...]);
    }
    
  3. Rollbacks

    • Use php artisan mongodb:migrate:rollback or define down() in migrations.
    • For complex rollbacks, use transactions:
      public function down()
      {
          DB::transaction(function () {
              Collection::drop('users');
              // Additional cleanup...
          });
      }
      

Schema Patterns

  • Indexes:
    $collection->index('email', ['unique' => true, 'sparse' => true]);
    
  • Field Types:
    $collection->field('metadata', ['type' => 'object']);
    $collection->field('tags', ['type' => 'array']);
    
  • Validation Rules:
    $collection->field('age', [
        'type' => 'int',
        'min' => 18,
        'max' => 120,
    ]);
    

Integration with Laravel

  1. Event Listeners Trigger migrations on registered or booted:

    public function boot()
    {
        if ($this->app->environment('production')) {
            Artisan::call('mongodb:migrate');
        }
    }
    
  2. Environment-Specific Migrations Use --env=testing flag or conditional logic:

    public function up()
    {
        if (app()->environment('local')) {
            Collection::create('logs', [...]);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Schema Drift

    • MongoDB lacks strict schemas. Use down() to revert changes carefully:
      public function down()
      {
          // Drop indexes first if needed
          DB::collection('users')->dropIndex('email');
          Collection::drop('users');
      }
      
  2. Transaction Limitations

    • MongoDB multi-document transactions require retryableWrites: true in connection config.
    • Test rollbacks locally with:
      php artisan mongodb:migrate:rollback --step=1
      
  3. Index Conflicts

    • Avoid duplicate index names. Use descriptive names:
      $collection->index('email_1', ['unique' => true]); // Suffix with _1 if needed
      

Debugging

  1. Dry Runs Use --pretend to preview changes:

    php artisan mongodb:migrate --pretend
    
  2. Logging Enable debug mode in config/mongodb-migrations.php:

    'debug' => env('APP_DEBUG', false),
    

    Check logs for failed migrations in storage/logs/laravel.log.

  3. MongoDB Shell Verification Manually verify schema changes:

    mongo --eval 'db.users.getIndexes()'
    

Extension Points

  1. Custom Commands Extend the base command:

    php artisan make:command CustomMongoMigrate
    

    Override handle() to add logic (e.g., pre-migration checks).

  2. Migration Events Listen for migrating or migrated events:

    Event::listen('migrating', function () {
        Log::info('Starting MongoDB migrations...');
    });
    
  3. Custom Schema Builders Extend Antimattr\MongoDBMigrations\Schema\Builder for reusable logic:

    class CustomBuilder extends Builder
    {
        public function addAuditFields()
        {
            $this->field('created_at', ['type' => 'date']);
            $this->field('updated_at', ['type' => 'date']);
        }
    }
    

    Use in migrations:

    $collection = new CustomBuilder($collectionName);
    $collection->addAuditFields();
    

Configuration Quirks

  1. Connection Binding Ensure config/database.php has the correct MongoDB connection:

    'connections' => [
        'mongodb' => [
            'driver' => 'mongodb',
            'host' => env('DB_HOST', '127.0.0.1'),
            // ...
        ],
    ],
    
  2. Migration Table The package uses migrations collection by default. Customize in config:

    'migrations_table' => 'custom_migrations',
    
  3. Timeouts Increase timeout for large migrations:

    'timeout' => 300, // 5 minutes
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle