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

doesntmattr/mongodb-migrations

Laravel package for running MongoDB database migrations. Provides migration commands and structure similar to Laravel’s SQL migrations, helping you version and deploy MongoDB schema/index changes safely across environments.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require doesntmattr/mongodb-migrations
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        DoesnTmattr\MongoDBMigrations\MongoDBMigrationsServiceProvider::class,
    ],
    
  2. Publish Config & Migrations

    php artisan vendor:publish --provider="DoesnTmattr\MongoDBMigrations\MongoDBMigrationsServiceProvider" --tag="migrations"
    

    This generates:

    • config/mongodb-migrations.php (default: migrations table name, connection)
    • database/migrations/mongodb/ (empty directory for MongoDB-specific migrations)
  3. First Migration Create a migration file:

    php artisan make:migration create_users_collection --collection
    

    Define schema in up():

    public function up()
    {
        Schema::create('users', function (Blueprint $collection) {
            $collection->index('email', ['unique' => true]);
            $collection->index('created_at');
            $collection->field('name', 'string');
            $collection->field('email', 'string');
            $collection->field('created_at', 'date');
        });
    }
    

    Run migrations:

    php artisan migrate
    

Implementation Patterns

Workflow Integration

  1. Schema Blueprints

    • Use Schema::create() for collections, Schema::table() for updates.
    • Fields: field(name, type, [options]) (e.g., string, int, array, object).
    • Indexes: $collection->index('field', ['unique' => true, 'sparse' => true]).
    • Example:
      Schema::table('products', function (Blueprint $collection) {
          $collection->field('price', 'decimal', ['precision' => 8, 'scale' => 2]);
          $collection->index('category');
      });
      
  2. Rollbacks

    • Define down() to revert changes:
      public function down()
      {
          Schema::dropIfExists('users');
      }
      
    • Run rollbacks:
      php artisan migrate:rollback
      
  3. Seeding Collections

    • Use Seeder classes with DB::collection('collection')->insert():
      public function run()
      {
          DB::collection('users')->insert([
              ['name' => 'John', 'email' => 'john@example.com'],
              ['name' => 'Jane', 'email' => 'jane@example.com'],
          ]);
      }
      
    • Run seeders:
      php artisan db:seed --class=UsersTableSeeder
      
  4. Multi-Database Support

    • Specify connection in config/mongodb-migrations.php:
      'connections' => [
          'mongodb' => 'mongodb',
          'secondary' => 'mongodb_secondary',
      ],
      
    • Use in migrations:
      Schema::connection('secondary')->create('backups', ...);
      
  5. Batch Migrations

    • Group migrations by feature (e.g., 2023_01_auth_migrations) and run selectively:
      php artisan migrate --path=/database/migrations/mongodb/2023_01
      

Common Use Cases

Use Case Implementation Command/Artisan
Create collection Schema::create('collection', ...) php artisan migrate
Add index $collection->index('field') php artisan migrate
Update field type Schema::table()->field('field', 'new_type') php artisan migrate
Drop collection Schema::dropIfExists('collection') php artisan migrate
Seed data DB::collection()->insert() in Seeder php artisan db:seed
Reset migrations Delete migrations table, run migrate:fresh php artisan migrate:fresh

Gotchas and Tips

Pitfalls

  1. Schema Limitations

    • No direct equivalent to SQL’s ALTER TABLE for adding/removing fields. Use down() to drop and up() to recreate.
    • Workaround: Store old data in a temporary collection during migration, then repopulate.
  2. Index Conflicts

    • MongoDB rejects duplicate index names. Ensure unique names:
      // Bad: Duplicate name
      $collection->index('email');
      $collection->index('email_1');
      
      // Good: Unique names
      $collection->index('email', ['name' => 'email_unique']);
      $collection->index('email', ['name' => 'email_text']);
      
  3. Connection Assumptions

    • Defaults to mongodb connection. Explicitly specify if using multiple:
      Schema::connection('custom_mongodb')->create('logs', ...);
      
  4. Migration Table

    • Uses a MongoDB collection (not SQL table) to track migrations. Ensure the migrations collection isn’t manually truncated.
  5. Field Type Mismatches

    • MongoDB is schema-less. Changing a field’s type (e.g., stringint) may corrupt existing data. Handle gracefully:
      public function up()
      {
          Schema::table('users', function (Blueprint $collection) {
              $collection->field('age', 'int', ['default' => 0]);
              // Handle existing string data:
              DB::collection('users')->updateMany(
                  ['age' => ['$exists' => false]],
                  ['$set' => ['age' => 0]]
              );
          });
      }
      

Debugging Tips

  1. Check Migration Status

    php artisan migrate:status
    
    • Lists pending/ran migrations. Useful for diagnosing stuck migrations.
  2. Inspect Collection Schema

    $collection = DB::collection('users');
    $indexes = $collection->getIndexInfo();
    dd($indexes);
    
  3. Log Migration Steps Add debug logs in up()/down():

    \Log::info('Creating collection with indexes: ' . json_encode($indexes));
    
  4. Test Locally with fresh

    php artisan migrate:fresh --env=testing
    
    • Resets the migrations collection and reapplies all migrations.

Extension Points

  1. Custom Migration Events Listen to migration events in EventServiceProvider:

    protected $listen = [
        'DoesnTmattr\MongoDBMigrations\Events\MigrationStarted' => [
           \App\Listeners\LogMigrationStart::class,
        ],
    ];
    
  2. Pre/Post-Migration Hooks Override Migrator class to add logic:

    class CustomMigrator extends \DoesnTmattr\MongoDBMigrations\Migrator
    {
        public function run($migration)
        {
            \Log::info("Running migration: {$migration->class}");
            parent::run($migration);
        }
    }
    

    Bind in AppServiceProvider:

    public function register()
    {
        $this->app->bind(
            \DoesnTmattr\MongoDBMigrations\Migrator::class,
            \App\CustomMigrator::class
        );
    }
    
  3. Custom Field Types Extend Blueprint for domain-specific fields:

    class CustomBlueprint extends \DoesnTmattr\MongoDBMigrations\Schema\Blueprint
    {
        public function embeddedDocument(string $name, array $schema)
        {
            $this->schema['$jsonSchema'] = [
                'bsonType' => 'object',
                'properties' => $schema,
            ];
            return $this;
        }
    }
    

    Use in migrations:

    Schema::create('profiles', function (CustomBlueprint $collection) {
        $collection->embeddedDocument('address', [
            'street' => ['bsonType' => 'string'],
            'city' => ['bsonType' => 'string'],
        ]);
    });
    
  4. Transaction Support (MongoDB 4.0+) Wrap migrations in sessions for atomicity:

    public function up()
    {
        $session = DB::startSession();
        try {
            Schema::create('orders', function (Blueprint $collection) {
                $collection->field('total', 'decimal');
            });
            DB::collection('orders')->insert([...]);
            $session->commitTransaction();
        } catch (\Exception $e) {
            $session->abortTransaction();
            throw $e;
        }
    }
    
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.
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views