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

xethron/migrations-generator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require --dev xethron/migrations-generator
    

    For Laravel <5.5, add Xethron\MigrationsGenerator\MigrationsGeneratorServiceProvider::class to config/app.php under providers.

  2. Publish Config (Optional)

    php artisan vendor:publish --provider="Xethron\MigrationsGenerator\MigrationsGeneratorServiceProvider"
    

    Config file: config/migrations-generator.php.

  3. First Use Case Generate migrations for an existing database:

    php artisan db:generate:migrations
    
    • Scans your database schema and creates migration files in database/migrations/.
    • Default output: YYYY_MM_DD_HHMMSS_create_tables.php.

Where to Look First

  • Config File: config/migrations-generator.php (customize table/column naming, excluded tables, etc.).
  • Artisan Commands:
    • db:generate:migrations (full schema generation).
    • db:generate:migration (generate for a specific table).
    • db:generate:seed (generate a seeder for existing data).
  • Example Output: Check database/migrations/ after running the command to see generated structure.

Implementation Patterns

Core Workflow

  1. Schema Analysis

    • Run php artisan db:generate:migration table_name to inspect a single table’s structure before full generation.
    • Use --dry-run flag to preview SQL without writing files:
      php artisan db:generate:migrations --dry-run
      
  2. Customizing Output

    • Naming Conventions: Modify table_name and column_name in config to match your project’s style (e.g., snake_case).
    • Excluded Tables: List tables to skip in config/migrations-generator.php under ignore_tables.
    • Foreign Keys: Enable/disable FK generation via generate_foreign_keys (default: true).
  3. Integration with Existing Migrations

    • Partial Generations: Generate migrations for new tables without overwriting existing ones.
    • Manual Edits: Post-generation, tweak migration files (e.g., add custom indexes, comments, or constraints) in up()/down() methods.
  4. Seeding Data

    • Generate a seeder for existing data:
      php artisan db:generate:seed --table=users
      
    • Outputs to database/seeds/YYYY_MM_DD_HHMMSS_TableSeeder.php.
  5. CI/CD Pipeline

    • Use in onboarding to bootstrap a new developer’s environment:
      php artisan db:generate:migrations && php artisan migrate
      

Advanced Patterns

  • Multi-Database Support

    • Configure multiple database connections in .env and use --connection=mysql flag:
      php artisan db:generate:migration --connection=mysql users
      
  • Custom Templates

    • Override default migration templates by publishing and modifying:
      php artisan vendor:publish --tag=migrations-generator-templates
      
    • Templates located in resources/views/vendor/migrations-generator/.
  • Post-Generation Hooks

    • Use Laravel’s registerCommands in a service provider to extend functionality:
      public function register()
      {
          $this->commands([
              \Xethron\MigrationsGenerator\Console\GenerateMigrations::class,
          ]);
          // Add custom logic here (e.g., auto-run migrations after generation)
      }
      
  • Testing

    • Test generated migrations with:
      php artisan migrate:fresh --env=testing
      php artisan db:generate:migrations --env=testing
      

Gotchas and Tips

Pitfalls

  1. Foreign Key Conflicts

    • Issue: Generated FKs may conflict with existing constraints or circular references.
    • Fix: Disable FK generation temporarily (generate_foreign_keys = false) or manually resolve in migration files.
  2. Reserved Keywords

    • Issue: Column names like key, group, or order may cause SQL syntax errors.
    • Fix: Wrap in backticks or rename via column_name config:
      'column_name' => [
          'key' => '`key`',
      ],
      
  3. Large Databases

    • Issue: Performance lag with complex schemas (e.g., hundreds of tables).
    • Fix: Generate tables in batches or exclude non-critical tables.
  4. Data Type Mismatches

    • Issue: Generated migrations may use incorrect data types (e.g., string instead of text).
    • Fix: Customize data_types mapping in config:
      'data_types' => [
          'tinyint(1)' => 'boolean',
          'varchar(255)' => 'string',
      ],
      
  5. Seeder Limitations

    • Issue: Generated seeders may not handle relationships or complex data.
    • Fix: Manually edit seeders or use --chunk flag for large datasets:
      php artisan db:generate:seed --table=users --chunk=100
      

Debugging Tips

  1. Dry Runs Use --dry-run to inspect SQL without file changes:

    php artisan db:generate:migration users --dry-run
    
  2. Verbose Output Enable debug mode for detailed logs:

    php artisan db:generate:migrations --verbose
    
  3. SQL Dump Check the raw SQL generated by the package:

    // In a custom command or service provider:
    $generator = new \Xethron\MigrationsGenerator\Generators\MigrationGenerator();
    $sql = $generator->getMigrationSql('users');
    
  4. Config Validation Validate config syntax before running:

    php artisan config:clear
    php artisan db:generate:migration users
    

Extension Points

  1. Custom Generators Extend the base generator by creating a subclass:

    namespace App\Generators;
    
    use Xethron\MigrationsGenerator\Generators\MigrationGenerator as BaseGenerator;
    
    class CustomMigrationGenerator extends BaseGenerator
    {
        protected function getColumnAttributes($column)
        {
            // Add custom logic (e.g., auto-add soft deletes)
            $attributes = parent::getColumnAttributes($column);
            $attributes['nullable'] = true;
            return $attributes;
        }
    }
    

    Register in AppServiceProvider@boot():

    $this->app->bind(
        \Xethron\MigrationsGenerator\Generators\MigrationGenerator::class,
        App\Generators\CustomMigrationGenerator::class
    );
    
  2. Event Listeners Listen for migration generation events to modify output:

    // In EventServiceProvider@boot():
    event(new \Xethron\MigrationsGenerator\Events\MigrationGenerated(
        $tableName,
        $migrationFile
    ));
    
  3. Database-Specific Tweaks Override the connection resolver for custom databases:

    $this->app->bind(
        \Illuminate\Database\Connection::class,
        function () {
            return \DB::connection('custom_db');
        }
    );
    
  4. Testing Hooks Mock the generator in tests:

    $generator = Mockery::mock(\Xethron\MigrationsGenerator\Generators\MigrationGenerator::class);
    $generator->shouldReceive('generate')->andReturn($migration);
    $this->app->instance(\Xethron\MigrationsGenerator\Generators\MigrationGenerator::class, $generator);
    
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.
croct/coding-standard
croct/plug-php
nqxcode/phpmorphy
boundwize/pyrameter
testo/facade
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle