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 Bundle Laravel Package

devture/mongodb-migrations-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require devture/mongodb-migrations-bundle
    

    Ensure Devture\MongoDBMigrationsBundle\DevtureMongoDBMigrationsBundle is enabled in config/bundles.php.

  2. Configuration: Add MongoDB connection details to config/packages/devture_mongodb_migrations.yaml:

    devture_mongodb_migrations:
        db: '%env(MONGODB_URL)%'
        migrations_namespace: 'App\Migrations'
        migrations_table: 'migrations'
    
  3. First Migration: Generate a migration file:

    php bin/console make:migration
    

    This creates a timestamped migration class in src/Migrations/ (e.g., 20240101000000_CreateUsersCollection.php).

  4. Run Migration:

    php bin/console mongodb:migrate
    

First Use Case

  • Schema Changes: Modify a collection’s schema (e.g., add an index, change field types). Example migration:
    namespace App\Migrations;
    
    use Devture\MongoDBMigrations\Migration;
    use Devture\MongoDBMigrations\MongoDB\Index;
    
    class AddEmailIndex extends Migration
    {
        public function up()
        {
            $this->collection('users')->ensureIndex(
                new Index('email', ['unique' => true])
            );
        }
    
        public function down()
        {
            $this->collection('users')->dropIndex('email_1');
        }
    }
    

Implementation Patterns

Workflows

  1. Migration Development:

    • Use php bin/console make:migration for boilerplate.
    • Extend Devture\MongoDBMigrations\Migration for custom logic.
    • Implement up() (changes) and down() (rollbacks).
  2. Integration with Laravel:

    • Artisan Commands: Bind the bundle’s commands to Laravel’s Artisan:
      // In AppServiceProvider@boot()
      $this->app->bind('mongodb.migrations.connection', function () {
          return \MongoDB\Client::fromConnectionString(env('MONGODB_URL'));
      });
      
    • Service Provider: Register the bundle’s services in AppServiceProvider:
      $this->app->register(\Devture\MongoDBMigrationsBundle\DevtureMongoDBMigrationsBundle::class);
      
  3. Environment-Specific Migrations:

    • Use php bin/console mongodb:migrate --env=production for targeted environments.
    • Store migrations in database/migrations/mongodb (Laravel convention).
  4. Seeding Data:

    • Combine with laravel/breeze or spatie/laravel-mongodb for post-migration seeding:
      public function up()
      {
          $this->collection('users')->insertOne([
              'name' => 'Admin',
              'email' => 'admin@example.com',
          ]);
      }
      

Patterns

  • Idempotent Migrations: Ensure up() is safe to rerun (e.g., check for existing indexes).
  • Transaction Wrappers: Use $this->transaction() for atomic operations:
    $this->transaction(function () {
        $this->collection('orders')->updateMany([], ['status' => 'pending']);
    });
    
  • Dependency Management: Order migrations by timestamp or use dependsOn():
    public function dependsOn()
    {
        return ['20240101000000_CreateUsersCollection'];
    }
    

Gotchas and Tips

Pitfalls

  1. Connection Issues:

    • Ensure MONGODB_URL is correctly set in .env (e.g., mongodb://user:pass@host:port/db).
    • Debug with php bin/console mongodb:migrate --debug.
  2. Migration Table Conflicts:

    • Default table name is migrations. Rename via config if needed:
      devture_mongodb_migrations:
          migrations_table: 'app_migrations'
      
  3. PHP 8+ Compatibility:

    • Use ^3.0 for PHP 8+ support. Avoid ^1.0 (PHP 5.6).
  4. Rollback Limitations:

    • down() may not reverse all changes (e.g., dropped collections). Document manual steps if needed.
  5. Namespace Collisions:

    • Ensure migrations_namespace in config matches your Laravel namespace (e.g., App\Migrations).

Debugging

  • Dry Runs: Use --dry-run to preview changes:
    php bin/console mongodb:migrate --dry-run
    
  • Logs: Enable debug mode in config/packages/devture_mongodb_migrations.yaml:
    devture_mongodb_migrations:
        debug: true
    

Tips

  1. Laravel Events: Trigger migrations on Migrating or Migrated events:

    // In EventServiceProvider
    protected $listen = [
        'Migrating' => [
            \App\Listeners\PreMigrationListener::class,
        ],
    ];
    
  2. Custom Migrations: Extend the base Migration class for reusable logic:

    namespace App\Migrations;
    
    use Devture\MongoDBMigrations\Migration;
    
    class BaseMigration extends Migration
    {
        protected function ensureIndex(string $collection, string $field, array $options = [])
        {
            $this->collection($collection)->ensureIndex(new \Devture\MongoDBMigrations\MongoDB\Index($field, $options));
        }
    }
    
  3. CI/CD Integration: Add to deployment pipeline:

    # .github/workflows/deploy.yml
    - run: php artisan mongodb:migrate --env=production --force
    
  4. Backup Strategy: Always back up MongoDB before running migrations in production:

    mongodump --uri="$MONGODB_URL" --out=/backup/$(date +%F)
    
  5. Testing: Use Laravel’s MigrateFresh or RefreshDatabase for testing:

    use Illuminate\Foundation\Testing\RefreshDatabase;
    
    class MigrationTest extends TestCase
    {
        use RefreshDatabase;
    }
    
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.
codifyo/ts-generator-bundle
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