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

Laravel Migrations Generator Laravel Package

kitloong/laravel-migrations-generator

Generate Laravel migration files from an existing database schema, including columns, indexes, and foreign keys. Works with MariaDB/MySQL, PostgreSQL, SQL Server, and SQLite. Generate all tables or target/ignore specific tables via Artisan.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation:

    composer require --dev kitloong/laravel-migrations-generator
    

    Laravel auto-registers the service provider; Lumen requires manual registration (see README).

  2. Verify Setup: Run php artisan migrate:generate --help to confirm the package is registered and options are available.

  3. First Use Case: Generate migrations for all tables in your default database:

    php artisan migrate:generate
    

    This creates individual migration files for each table in database/migrations/, including foreign keys, indexes, and constraints.


Implementation Patterns

Core Workflows

  1. Generating Migrations for Specific Tables:

    php artisan migrate:generate --tables="users,posts,comments"
    
    • Useful for partial database reverse-engineering (e.g., legacy systems or incremental migrations).
  2. Excluding Tables:

    php artisan migrate:generate --ignore="logs,failed_jobs"
    
    • Skips system tables or temporary tables during generation.
  3. Custom Output Path:

    php artisan migrate:generate --path="database/migrations/custom"
    
    • Organize migrations by feature/module (e.g., custom/auth, custom/reports).
  4. Squashing Migrations:

    php artisan migrate:generate --squash
    
    • Combines all tables into a single migration file (ideal for initial setup or large databases).
    • Note: Foreign keys are added in a separate squashed migration by default.
  5. Connection-Specific Migrations:

    php artisan migrate:generate --connection="secondary"
    
    • Generate migrations for a secondary database (e.g., analytics or reporting DBs).
  6. Date Control:

    php artisan migrate:generate --date="2024-01-01 00:00:00"
    
    • Align migrations with a specific timeline (e.g., for versioned deployments).
  7. Schema Checks:

    php artisan migrate:generate --with-has-table
    
    • Adds Schema::hasTable() checks to migrations, preventing errors in environments where tables may already exist.

Integration Tips

  1. Custom Templates: Override default migration templates by specifying a custom path:

    php artisan migrate:generate --template-path="resources/templates/migrations"
    
    • Useful for enforcing team-specific conventions (e.g., custom docblocks or table prefixes).
  2. Foreign Key Handling:

    • Ensure all referenced tables are included in --tables or generated first.
    • Use --skip-foreign-keys to generate tables without constraints, then add them later:
      php artisan migrate:generate --tables="users" --skip-foreign-keys
      php artisan migrate:generate --tables="posts" --skip-foreign-keys
      php artisan migrate:generate --tables="users,posts" --skip-foreign-keys=false
      
  3. Collation and Encoding: Preserve database collation with:

    php artisan migrate:generate --use-db-collation
    
    • Critical for multilingual applications or legacy databases.
  4. Vendor Migrations: Exclude vendor-specific tables (e.g., Laravel’s failed_jobs) with:

    php artisan migrate:generate --skip-vendor
    
  5. Views and Stored Procedures: Generate migrations for views or procedures:

    php artisan migrate:generate --skip-views=false --skip-proc=false
    
    • Useful for reporting databases or complex schemas.
  6. Batch Logging: Assign migrations to a batch for ordering:

    php artisan migrate:generate --log-with-batch=0
    
    • Ensures migrations run in a specific sequence (e.g., batch 0 for initial setup).

Gotchas and Tips

Pitfalls

  1. Circular Dependencies:

    • If tables reference each other via foreign keys, the generator may fail or produce incorrect migrations.
    • Fix: Manually order tables or use --skip-foreign-keys to generate tables first, then add constraints separately.
  2. Reserved Keywords:

    • Database column names like order, group, or user may conflict with PHP/Laravel syntax.
    • Fix: Use --default-index-names or --default-fk-names to generate Laravel-friendly names:
      php artisan migrate:generate --default-index-names --default-fk-names
      
  3. Large Databases:

    • Generating migrations for thousands of tables can be slow or memory-intensive.
    • Fix: Use --tables to limit scope or --squash to reduce file count.
  4. Connection Mismatches:

    • Running migrate:generate against a connection that doesn’t match config/database.php will fail silently.
    • Fix: Verify the connection name with:
      php artisan tinker
      >>> \DB::connection()->getDatabaseName();
      
  5. Schema Changes Mid-Generation:

    • Modifying the database while generating migrations can corrupt output.
    • Fix: Run in a controlled environment or use --skip-log to avoid writing to the migrations table.
  6. PostgreSQL-Specific Issues:

    • Complex PostgreSQL features (e.g., jsonb, uuid) may not map cleanly to Laravel’s schema builder.
    • Fix: Post-process migrations to handle unsupported types or use raw SQL:
      $table->text('metadata')->comment('JSON data');
      

Debugging Tips

  1. Dry Run: Use --path="tmp/migrations" to test generation without overwriting production files.

  2. Verbose Output: Enable debug mode to see SQL queries:

    php artisan migrate:generate --tables="users" --verbose
    
  3. Template Inspection: Check the generated template at:

    vendor/kitloong/laravel-migrations-generator/src/Template/Blueprint.php
    
    • Customize by copying the template to your project and using --template-path.
  4. Foreign Key Errors: If foreign keys fail to generate, manually inspect the database schema for:

    • Missing referenced tables.
    • Incorrect column types (e.g., int vs. bigint).
    • Case sensitivity issues (e.g., UserID vs. user_id).
  5. SQLite Quirks:

    • SQLite ignores foreign key constraints by default. Add this to your migration:
      Schema::connection('sqlite')->enableForeignKeyConstraints();
      

Extension Points

  1. Custom Migration Logic: Extend the generator by publishing and modifying the service provider:

    php artisan vendor:publish --provider="KitLoong\MigrationsGenerator\MigrationsGeneratorServiceProvider"
    
    • Override generate() in app/Providers/MigrationsGeneratorServiceProvider.php to add pre/post-processing.
  2. Event Listeners: Listen for migration generation events to modify output:

    use KitLoong\MigrationsGenerator\Events\MigrationGenerated;
    
    Event::listen(MigrationGenerated::class, function ($event) {
        // Modify $event->migration->getContent()
    });
    
  3. Command Customization: Create a custom command extending GenerateMigrationsCommand:

    use KitLoong\MigrationsGenerator\Console\GenerateMigrationsCommand;
    
    class CustomGenerateMigrationsCommand extends GenerateMigrationsCommand {
        protected function getOptions() {
            return array_merge(parent::getOptions(), [
                ['custom-option', 'c', InputOption::VALUE_OPTIONAL, 'Custom option description'],
            ]);
        }
    }
    
  4. Schema Blueprint Extensions: Add custom column types or modifiers by extending KitLoong\MigrationsGenerator\Template\Blueprint:

    class CustomBlueprint extends Blueprint {
        public function customColumn($name, $type) {
            // Custom logic
        }
    }
    

    Register it in your service provider’s boot() method.

  5. Post-Generation Hooks: Use Laravel’s migrated event to run logic after generation:

    Event::listen('migrated', function ($migration) {
        // Example: Optimize tables or run post-migration tasks
    });
    
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