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 Implicit Migrations Laravel Package

toramanlis/laravel-implicit-migrations

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require toramanlis/laravel-implicit-migrations
    

    Publish the config file:

    php artisan vendor:publish --provider="Toramanlis\ImplicitMigrations\ImplicitMigrationsServiceProvider"
    
  2. First Use Case: Run the implicit:migrate Artisan command to generate migrations for all models in app/Models:

    php artisan implicit:migrate
    

    This inspects models (e.g., User.php) and creates corresponding migrations in database/migrations/.

  3. Key Config: Check config/implicit-migrations.php for:

    • model_paths: Directories to scan (default: app/Models).
    • migration_namespace: Custom namespace for generated migrations.
    • ignore_models: Exclude specific models (e.g., ['User', 'Role']).

Implementation Patterns

Workflow Integration

  1. Onboarding New Models:

    • Add a model (e.g., app/Models/Post.php).
    • Run php artisan implicit:migrate to auto-generate a migration.
    • Customize the generated migration (e.g., add indexes, constraints) before running it.
  2. Seeding and Factories:

    • Use the generated migrations as a foundation, then pair with factories (e.g., DatabaseSeeder):
      // database/factories/PostFactory.php
      public function definition()
      {
          return [
              'title' => 'Test Post',
              'body'  => 'Test content',
          ];
      }
      
  3. Partial Updates:

    • Modify a model (e.g., add $fillable = ['new_field'] to User.php).
    • Re-run php artisan implicit:migrate to update the migration file.
    • Tip: Use --force to overwrite existing migrations:
      php artisan implicit:migrate --force
      
  4. Rollbacks and Re-runs:

    • Rollback with php artisan migrate:rollback.
    • Re-run migrations with php artisan migrate (generated files are idempotent).
  5. Testing:

    • Use php artisan implicit:migrate --dry-run to preview changes without writing files.
    • Test migrations in CI by running:
      php artisan implicit:migrate && php artisan migrate:fresh --env=testing
      

Advanced Patterns

  1. Custom Migration Logic:

    • Extend the generator by publishing the service provider and overriding methods in app/Providers/ImplicitMigrationsServiceProvider.php:
      public function boot()
      {
          $this->app->make('Toramanlis\ImplicitMigrations\Generators\MigrationGenerator')
              ->setCustomLogic(function ($table, $model) {
                  // Add custom columns or logic
                  $table->unique('email');
              });
      }
      
  2. Excluding Specific Fields:

    • Use $hidden or $guarded in models to exclude fields:
      protected $hidden = ['api_token'];
      
    • Or configure in implicit-migrations.php:
      'ignore_attributes' => ['remember_token', 'created_at', 'updated_at'],
      
  3. Foreign Keys:

    • Ensure relationships are defined in models (e.g., belongsTo, hasMany).
    • The generator will auto-detect and add foreign keys where possible.
  4. Soft Deletes:

    • Add use SoftDeletes; to models and set $dates = ['deleted_at'].
    • The generator will include softDeletes() in the migration.
  5. Timestamps:

    • Disable auto-timestamps in models with public $timestamps = false to exclude created_at/updated_at.

Gotchas and Tips

Common Pitfalls

  1. Overwriting Migrations:

    • Running --force will delete existing migrations. Use cautiously in shared environments.
    • Solution: Backup migrations or use Git to track changes.
  2. Circular Dependencies:

    • If models reference each other (e.g., User has Post, Post has User), migrations may fail.
    • Solution: Manually order migrations or use --force to regenerate.
  3. Reserved Keywords:

    • Column names like key, table, or group may cause SQL errors.
    • Solution: Rename attributes in models or use backticks in custom logic.
  4. Case Sensitivity:

    • Generated migrations use snake_case for column names (e.g., user_id).
    • Tip: Ensure model attributes match this convention.
  5. Database-Specific Syntax:

    • The generator uses Laravel’s query builder, but some databases (e.g., SQLite) lack features like foreign keys.
    • Tip: Test migrations on your target database early.

Debugging Tips

  1. Dry Run: Use --dry-run to inspect generated SQL without writing files:

    php artisan implicit:migrate --dry-run
    
  2. Verbose Output: Enable debug mode in implicit-migrations.php:

    'debug' => true,
    

    Or use:

    php artisan implicit:migrate -v
    
  3. Log Inspection: Check storage/logs/laravel.log for errors during generation.

  4. Model Inspection: Verify model attributes with:

    php artisan tinker
    >>> \Toramanlis\ImplicitMigrations\Support\Inspector::inspect(\App\Models\User::class);
    

Extension Points

  1. Custom Generators:

    • Override the default generator by binding a new class in the service provider:
      $this->app->bind('implicit.migration.generator', function () {
          return new \App\Generators\CustomMigrationGenerator();
      });
      
  2. Pre/Post-Generation Hooks:

    • Use events to modify migrations before/after generation:
      // In EventServiceProvider
      public function boot()
      {
          ImplicitMigrations::generating(function ($migration) {
              $migration->prepend("<?php\n\nuse Illuminate\Support\Facades\Schema;\n");
          });
      }
      
  3. Model Metadata:

    • Add custom metadata to models for advanced control:
      class User extends Model
      {
          protected static $implicitMigrationOptions = [
              'ignore' => ['password'],
              'custom' => [
                  'indexes' => ['email'],
                  'engine' => 'InnoDB',
              ],
          ];
      }
      
  4. Database-Specific Config:

    • Configure per-database settings in implicit-migrations.php:
      'connections' => [
          'mysql' => [
              'engine' => 'InnoDB',
          ],
          'sqlite' => [
              'foreign_keys' => false,
          ],
      ],
      

Pro Tips

  1. Pair with Laravel Forge/Laravel Envoyer:

    • Automate migration generation in deployment pipelines by adding:
      php artisan implicit:migrate --force
      php artisan migrate --force
      

    to your deployment script.

  2. Seeders and Factories:

    • Generate factories alongside migrations for consistency:
      php artisan make:factory UserFactory --model=User
      
    • Use the same --force flag to regenerate factories when models change.
  3. Schema Dumps:

    • For large applications, dump the schema after generation:
      php artisan schema:dump
      
    • Store the dump in version control to ensure consistency across environments.
  4. CI/CD Optimization:

    • Cache generated migrations in CI to avoid re-generating on every run:
      if [ ! -f database/migrations/generated_at ]; then
          php artisan implicit:migrate --force
          touch database/migrations/generated_at
      fi
      
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony