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

devture/mongodb-migrations

Laravel-friendly MongoDB migration runner that manages schema/data changes with versioned migration classes and CLI commands. Helps apply, track, and rollback database updates across environments in a predictable way.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require devture/mongodb-migrations
    

    Publish the migration config (optional but recommended):

    php artisan vendor:publish --provider="Devture\MongoDBMigrations\MongoDBMigrationsServiceProvider" --tag="config"
    
  2. Configuration Update config/mongodb-migrations.php with your MongoDB connection details (use Laravel’s existing MongoDB config if available):

    'connection' => 'mongodb',
    'database' => 'your_database_name',
    'collection' => 'migrations',
    
  3. First Migration Create a migration file:

    php artisan make:mongo:migration create_users_collection
    

    This generates a file in database/migrations/mongodb/. Define your schema in the up() method:

    public function up()
    {
        Schema::create('users', function (CreateCollection $collection) {
            $collection->index('email', ['unique' => true]);
            $collection->index('created_at');
        });
    }
    
  4. Run Migrations Execute migrations:

    php artisan mongodb:migrate
    

Implementation Patterns

Workflow Integration

  1. Schema Management Use Schema facade for collection operations:

    // Create a collection with indexes
    Schema::create('products', function (CreateCollection $collection) {
        $collection->index('sku', ['unique' => true, 'sparse' => true]);
        $collection->index('price');
    });
    
    // Drop a collection
    Schema::drop('products');
    
  2. Batch Migrations Group related migrations in a single file (e.g., 2023_01_01_000000_create_initial_schema.php) for atomicity:

    public function up()
    {
        Schema::create('posts');
        Schema::create('comments');
    }
    
  3. Rollbacks Define down() for reversible migrations:

    public function down()
    {
        Schema::drop('users');
    }
    

    Run rollbacks:

    php artisan mongodb:rollback
    
  4. Seeding Post-Migration Use Laravel’s Seeder class to populate data after migrations:

    public function run()
    {
        DB::collection('users')->insert([
            ['name' => 'Admin', 'email' => 'admin@example.com'],
        ]);
    }
    

    Execute with:

    php artisan db:seed --class=UsersTableSeeder
    

Advanced Patterns

  1. Custom Migration Logic Extend Migration class for reusable logic:

    use Devture\MongoDBMigrations\Migration;
    
    class AddTimestampIndexes extends Migration
    {
        public function up()
        {
            Schema::collection('posts')->index('created_at');
            Schema::collection('posts')->index('updated_at');
        }
    }
    
  2. Environment-Specific Migrations Use Laravel’s environment detection in migrations:

    if (app()->environment('production')) {
        Schema::collection('orders')->index('customer_id');
    }
    
  3. Migration Events Listen for migration events (e.g., Migrating, Migrated) via Laravel’s event system:

    Event::listen(Migrating::class, function (Migrating $event) {
        Log::info('Starting MongoDB migrations...');
    });
    
  4. Testing Migrations Use Laravel’s testing helpers to assert migration states:

    public function test_migration_creates_collection()
    {
        Artisan::call('mongodb:migrate');
        $this->assertTrue(Schema::hasCollection('users'));
    }
    

Gotchas and Tips

Common Pitfalls

  1. Collection Existence Assumptions

    • Issue: Assuming a collection exists before adding indexes.
    • Fix: Use Schema::hasCollection() or wrap in try-catch:
      if (!Schema::hasCollection('users')) {
          Schema::create('users');
      }
      Schema::collection('users')->index('email');
      
  2. Index Naming Conflicts

    • Issue: MongoDB rejects duplicate index names.
    • Fix: Use unique names or drop existing indexes first:
      Schema::collection('products')->dropIndex('price_1');
      Schema::collection('products')->index('price');
      
  3. Migration Order Dependencies

    • Issue: Migrations failing due to missing collections.
    • Fix: Order migrations logically or use down() to clean up.
  4. Large Data Migrations

    • Issue: Slow performance with bulk operations.
    • Fix: Batch inserts/updates or use unordered() for non-critical writes:
      DB::collection('users')->insertMany($users, ['ordered' => false]);
      

Debugging Tips

  1. Migration Logs Enable verbose output:

    php artisan mongodb:migrate --verbose
    

    Or check Laravel’s log (storage/logs/laravel.log) for errors.

  2. Schema Inspection Dump collection schema:

    $schema = Schema::getCollectionSchema('users');
    dd($schema);
    
  3. Rollback Debugging If rollbacks fail, manually inspect the migrations collection:

    dd(DB::collection('migrations')->find());
    

Extension Points

  1. Custom Migration Table Override the default migrations collection name in config:

    'collection' => 'app_migrations',
    
  2. Migration Resolver Extend MigrationResolver to customize migration discovery:

    // app/Providers/MongoDBMigrationsServiceProvider.php
    public function register()
    {
        $this->app->bind(MigrationResolver::class, function () {
            return new CustomMigrationResolver();
        });
    }
    
  3. Pre/Post Migration Hooks Use Laravel’s register method in a service provider to add hooks:

    public function register()
    {
        MongoDBMigrations::extend(function ($migrator) {
            $migrator->before(function () {
                Log::info('Pre-migration hook');
            });
        });
    }
    
  4. Custom Commands Extend the migrator with new commands (e.g., mongodb:migrate:status):

    Artisan::command('mongodb:migrate:status', function () {
        $this->info('Migration status: ' . MongoDBMigrations::status());
    });
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity