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

Migrations Laravel Package

doctrine/migrations

Doctrine Migrations manages database schema changes via versioned migrations for PHP projects. Generate, run, and track migration scripts, integrate with Doctrine DBAL/ORM, and safely evolve schemas across environments with robust CLI tooling and documentation.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install the package via Composer:

    composer require doctrine/dbal doctrine/migrations
    

    (Laravel already includes doctrine/dbal via Eloquent, so only doctrine/migrations is needed.)

  2. Publish the migration configuration (optional but recommended):

    php artisan vendor:publish --provider="Doctrine\Migrations\ServiceProvider"
    

    This creates a config/doctrine_migrations.php file.

  3. Generate your first migration:

    php artisan doctrine:migrations:generate --name="CreateUsersTable" --path="database/migrations"
    

    This creates a new migration file in database/migrations/ with a timestamp prefix.

  4. Run the migration:

    php artisan doctrine:migrations:migrate
    

First Use Case: Schema Changes

  • Modify your database/migrations/ file (e.g., add a new column to users table).
  • Run:
    php artisan doctrine:migrations:migrate
    

Implementation Patterns

Daily Workflow

  1. Creating Migrations:

    • Use doctrine:migrations:generate for new migrations.
    • Manually edit the generated file for complex changes (e.g., multi-table operations).
    • Example:
      // database/migrations/YYYYMMDDHHMMSS_CreateUsersTable.php
      public function up(Schema $schema): void
      {
          $this->addSql('CREATE TABLE users (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
      }
      
      public function down(Schema $schema): void
      {
          $this->addSql('DROP TABLE users');
      }
      
  2. Running Migrations:

    • Migrate all pending migrations:
      php artisan doctrine:migrations:migrate
      
    • Migrate to a specific version:
      php artisan doctrine:migrations:migrate --to=20230101000000
      
    • Rollback the last migration:
      php artisan doctrine:migrations:migrate --direction=down
      
  3. Generating Migrations from Schema Changes:

    • Use doctrine:migrations:diff to auto-generate migrations from existing schema changes:
      php artisan doctrine:migrations:diff --path="database/migrations"
      
  4. Executing Raw SQL:

    • For one-off SQL changes, use doctrine:migrations:execute:
      php artisan doctrine:migrations:execute --sql="ALTER TABLE users ADD COLUMN email VARCHAR(255)"
      

Integration with Laravel

  • Service Provider: Register the migrations service in config/app.php under providers:
    Doctrine\Migrations\ServiceProvider::class,
    
  • Custom Configuration: Override defaults in config/doctrine_migrations.php:
    'migrations_paths' => [
        'DoctrineMigrations' => __DIR__.'/../database/migrations',
    ],
    'table_name' => 'migrations_versions',
    'connection' => 'mysql', // Use your Laravel DB connection
    

Advanced Patterns

  1. Dependency Injection:

    • Access the Migration class in Laravel services:
      use Doctrine\Migrations\Migration;
      use Doctrine\DBAL\Schema\Schema;
      
      class CustomMigration extends Migration
      {
          public function up(Schema $schema): void
          {
              // Custom logic
          }
      }
      
  2. Custom Commands:

    • Extend Doctrine\Migrations\Tools\Console\Command\AbstractCommand to create custom CLI tools.
  3. Event Listeners:

    • Hook into migration events (e.g., preMigration, postMigration) via Doctrine\Migrations\Event\Events.

Gotchas and Tips

Common Pitfalls

  1. Schema Name Handling:

    • If using schema names (e.g., schema_name.table_name), ensure the DiffGenerator is configured to handle them:
      $diffGenerator = new DiffGenerator();
      $diffGenerator->setSchemaName('schema_name'); // Explicitly set schema
      
    • Fix: Update config/doctrine_migrations.php to include schema names in diffs:
      'diff_generator' => [
          'schema_name' => 'your_schema',
      ],
      
  2. Down Migration Failures:

    • Always test down() migrations locally. Use --dry-run to preview:
      php artisan doctrine:migrations:migrate --dry-run
      
    • Tip: Use transactions for down() migrations to ensure rollback consistency.
  3. Connection Issues:

    • Ensure the connection in config/doctrine_migrations.php matches your Laravel .env DB settings.
    • Debug: Use --verbose flag for detailed output:
      php artisan doctrine:migrations:migrate --verbose
      
  4. Migration Table Conflicts:

    • The default migration table (migrations_versions) might conflict with Laravel’s own migrations. Rename it in config:
      'table_name' => 'custom_migration_versions',
      
  5. Large Migrations:

    • Avoid monolithic migrations. Break them into smaller, atomic changes for easier debugging.

Debugging Tips

  1. Enable SQL Logging:

    • Add this to config/doctrine_migrations.php:
      'logging' => true,
      'logging_level' => 'DEBUG',
      
    • Logs will appear in storage/logs/laravel.log.
  2. Check Migration Status:

    • Inspect the migrations_versions table directly:
      SELECT * FROM migrations_versions ORDER BY version_number DESC;
      
  3. Reset Migrations:

    • To start fresh, drop the migration table and re-run migrations:
      php artisan doctrine:migrations:execute --sql="DROP TABLE migrations_versions"
      php artisan doctrine:migrations:migrate
      

Extension Points

  1. Custom Migration Classes:

    • Extend Doctrine\Migrations\AbstractMigration for reusable logic:
      class BaseMigration extends AbstractMigration
      {
          protected function createTable(string $tableName, array $columns): void
          {
              $this->addSql(sprintf('CREATE TABLE %s (%s)', $tableName, implode(', ', $columns)));
          }
      }
      
  2. Custom Diff Generator:

    • Override Doctrine\Migrations\Tools\Console\Command\DiffCommand to filter tables/schemas:
      protected function getDiffGenerator(): DiffGenerator
      {
          $generator = new DiffGenerator();
          $generator->setFilterTableExpression('/^(?!ignored_).*/'); // Skip ignored tables
          return $generator;
      }
      
  3. Pre/Post Migration Hooks:

    • Use events to run logic before/after migrations:
      $eventManager = $migration->getEventManager();
      $eventManager->addEventListener(
          Events::preMigration,
          function (PreMigrationEventArgs $event) {
              // Logic before migration
          }
      );
      
  4. Custom SQL Formatting:

    • Override the SqlFormatter to customize SQL output (e.g., for readability):
      $formatter = new SqlFormatter();
      $formatter->setLineLength(120); // Wider lines
      $migration->setSqlFormatter($formatter);
      

Laravel-Specific Quirks

  1. Artisan Command Namespace:

    • Ensure custom commands are namespaced under App\Console\Commands and registered in app/Console/Kernel.php.
  2. Database Transactions:

    • Laravel’s DB::transaction() may conflict with Doctrine’s migrations. Use doctrine:migrations:migrate --all-or-nothing to wrap migrations in a transaction.
  3. Schema Introspection:

    • If using Eloquent models, ensure Schema::getTableName() matches your actual table names (e.g., singular/plural conventions).
  4. Environment-Specific Migrations:

    • Use Laravel’s environment variables to conditionally run migrations:
      if (app()->environment('local')) {
          $this->addSql('CREATE INDEX idx_users_name ON users(name)');
      }
      
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.
phpshko/laravel-livewire-depdrop
larasell-dev/larasell
calliostro/spotify-bundle
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer