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

Php My Migration Laravel Package

adly-nady/php-my-migration

Laravel package to generate migrations (and optional Eloquent models) from an existing MySQL database. Detects column types, keys, indexes, foreign keys, timestamps/soft deletes; supports batch processing, custom paths, overwrite, and connections.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require adly-nady/php-my-migration
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        AdlyNady\MyMigration\MyMigrationServiceProvider::class,
    ],
    
  2. Publish Config

    php artisan vendor:publish --provider="AdlyNady\MyMigration\MyMigrationServiceProvider" --tag="config"
    

    Configure config/mymigration.php (adjust database and migration_path as needed).

  3. First Run

    php artisan my:migration:generate
    

    This scans your database and generates migration files for existing tables in database/migrations/.

  4. Verify Output Check the generated migrations in database/migrations/ and inspect the schema definitions.


Where to Look First

  • Config File: config/mymigration.php – Adjust database_connection, migration_path, and ignore_tables.
  • Artisan Commands:
    • php artisan my:migration:generate – Generate migrations for existing tables.
    • php artisan my:migration:sync – Sync existing tables with generated migrations (e.g., after manual edits).
  • Helper Methods:
    use AdlyNady\MyMigration\Facades\MyMigration;
    $migration = MyMigration::generateForTable('users'); // Generate a single table's migration.
    

First Use Case: Backfilling Migrations

Scenario: You inherited a project with an existing MySQL database but no Laravel migrations.

  1. Run php artisan my:migration:generate to auto-generate migrations for all tables.
  2. Review the generated files (especially up() and down() methods) for accuracy.
  3. Run php artisan migrate to create the tables (if they don’t exist) or sync them.

Implementation Patterns

Workflows

1. Generating Migrations for Existing Tables

  • Full Database Scan:
    php artisan my:migration:generate
    
    Generates migrations for all tables in the configured database.
  • Single Table:
    MyMigration::generateForTable('products')->save();
    
    Useful for selective backfilling.

2. Syncing Changes

  • After manually editing a generated migration (e.g., adding indexes), sync it with the database:
    php artisan my:migration:sync
    
    This updates the database schema to match the migration file.

3. Ignoring Tables

Configure ignore_tables in config/mymigration.php to exclude tables like:

'ignore_tables' => [
    'migrations',
    'failed_jobs',
    'sessions',
],

4. Customizing Migration Templates

Override the default migration template by publishing and modifying:

php artisan vendor:publish --provider="AdlyNady\MyMigration\MyMigrationServiceProvider" --tag="templates"

Edit resources/views/vendor/mymigration/migration.stub.


Integration Tips

Laravel Ecosystem

  • Use with Laravel Schema Builder: Generated migrations can be extended with Laravel’s schema methods (e.g., $table->foreignId()).

    Schema::table('orders', function (Blueprint $table) {
        $table->foreignId('user_id')->constrained();
    });
    
  • Seeders: After generating migrations, create seeders for existing data:

    public function run()
    {
        DB::table('users')->insert([
            ['name' => 'Admin', 'email' => 'admin@example.com'],
        ]);
    }
    

CI/CD

  • Add to Deployment Pipeline: Include php artisan my:migration:generate in your CI/CD script to keep migrations in sync with the database schema. Example (GitHub Actions):
    - name: Generate migrations
      run: php artisan my:migration:generate
    - name: Commit changes
      run: git config --global user.name "CI Bot" && git config --global user.email "ci@example.com" && git add database/migrations && git commit -m "chore: sync migrations" && git push
    

Testing

  • Test Generated Migrations: Use Laravel’s Schema::hasTable() and Schema::hasColumn() in tests to verify migrations:
    public function test_users_table_exists()
    {
        $this->assertTrue(Schema::hasTable('users'));
        $this->assertTrue(Schema::hasColumn('users', 'email'));
    }
    

Gotchas and Tips

Pitfalls

  1. Data Type Mismatches:

    • The package infers data types from MySQL (e.g., INTinteger(), VARCHAR(255)string()). Tip: Manually review generated migrations for edge cases like ENUM or SET fields, which may not map perfectly.
    • Fix: Edit the migration file or use php artisan my:migration:sync to update the database.
  2. Foreign Key Constraints:

    • Generated migrations may not include foreign key constraints if they don’t exist in the database.
    • Tip: Add constraints manually or use php artisan my:migration:sync --with-foreign-keys (if supported in future versions).
  3. Transaction Conflicts:

    • Running php artisan migrate after generating migrations for a large database may fail due to transaction size limits.
    • Fix: Disable transactions in config/database.php or run migrations in batches.
  4. Case Sensitivity:

    • MySQL table/column names are case-sensitive on some systems (e.g., Linux). Ensure consistency in generated migrations.
    • Tip: Configure lower_case_table_names in my.cnf if needed.
  5. Overwriting Existing Migrations:

    • Regenerating migrations for a table will overwrite the file. Tip: Use php artisan my:migration:generate --dry-run to preview changes before overwriting.

Debugging

  1. Enable Verbose Output:

    php artisan my:migration:generate --verbose
    

    Shows detailed SQL queries and table analysis.

  2. Check Logs: Inspect storage/logs/laravel.log for errors during generation or syncing.

  3. Compare with Database: Use a tool like TablePlus or Adminer to manually verify the generated schema matches the database.

  4. Handle Custom Storage Engines: If a table uses a non-InnoDB engine (e.g., MyISAM), the package may not generate accurate constraints.

    • Workaround: Add engine specifications manually:
      $table->engine = 'MyISAM';
      

Tips

  1. Partial Generation: Generate migrations for specific schemas only:

    MyMigration::generateForTables(['users', 'products']);
    
  2. Exclude Views/Procedures: The package focuses on tables. For views or stored procedures, use raw SQL or tools like Doctrine DBAL.

  3. Version Control: Commit generated migrations to version control, but document manual changes in a README.md or comment block.

  4. Performance: For large databases, optimize by:

    • Running php artisan my:migration:generate in a maintenance mode:
      php artisan down --secret=your-secret
      php artisan my:migration:generate
      php artisan up --secret=your-secret
      
    • Using --chunk (if supported in future versions) to process tables in batches.
  5. Extending Functionality:

    • Custom Data Type Mappers: Override the default type mapping by extending AdlyNady\MyMigration\Contracts\TypeMapper and binding your implementation in the service provider.
    • Pre/Post-Generation Hooks: Use Laravel’s registering and registered events in the service provider to add logic before/after migration generation.
  6. Collaboration:

    • Team Workflow: Assign one developer to review generated migrations before committing to avoid merge conflicts.
    • Document Assumptions: Add comments in generated migrations if you’ve made manual adjustments (e.g., # Manually added: $table->unique('slug');).
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