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 Model Builder Laravel Package

jimbolino/laravel-model-builder

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require jimbolino/laravel-model-builder:dev-master
    

    Register the service provider in config/app.php:

    'providers' => [
        // ...
        Jimbolino\Laravel\ModelBuilder\ModelBuilderServiceProvider::class,
    ],
    
  2. First Run Add the route to routes/web.php:

    Route::get('/generate/models', '\\Jimbolino\\Laravel\\ModelBuilder\\ModelGenerator5@start');
    

    Visit /generate/models in your browser to generate models in storage/models.

  3. Manual Integration Copy generated models from storage/models to your app/Models directory. Use tools like Beyond Compare or WinMerge to merge changes with existing models.


First Use Case

Reverse-Engineer a Legacy Database

  • Use this package to auto-generate Eloquent models for an existing MySQL database where manual model creation is time-consuming.
  • Ideal for rapid prototyping or migrating legacy systems to Laravel.

Implementation Patterns

Workflow Integration

  1. Generate Models Run the generator via the web route or CLI (if extended). Models are created with:

    • Basic CRUD attributes ($fillable, $guarded).
    • Relationships (hasOne, belongsTo, hasMany, etc.) inferred from foreign keys.
    • Timestamps and soft deletes detected (though not always accurate).
  2. Manual Refinement

    • Copy and Override: Use the generated models as a starting point, then refine them in app/Models.
    • Partial Generation: Generate models for specific tables only by modifying the generator’s table selection logic (e.g., filter by prefix or schema).
  3. Testing Generated Models

    • Write feature tests to validate auto-generated relationships and attributes.
    • Example:
      public function test_auto_generated_relationships()
      {
          $user = User::find(1);
          $this->assertInstanceOf(User::class, $user);
          $this->assertNotNull($user->posts); // hasMany relationship
      }
      

Advanced Patterns

  1. Customizing Generation Extend the generator by overriding methods in ModelGenerator5:

    // Example: Modify how timestamps are handled
    public function shouldUseTimestamps($table)
    {
        return false; // Disable timestamps for all tables
    }
    
  2. Post-Generation Processing Use Laravel’s model events (created, saved) to add logic after generation:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        Model::created(function ($model) {
            if (str_contains($model->getTable(), 'legacy_')) {
                $model->addGlobalScope('legacyScope', function (Builder $query) {
                    $query->where('active', 1);
                });
            }
        });
    }
    
  3. CI/CD Integration

    • Add a script to your composer.json to automate model generation and updates:
      "scripts": {
          "generate:models": "php artisan route:list | grep generate/models && curl http://localhost/generate/models || echo 'Models already up-to-date'"
      }
      
    • Run during deployment to sync models with the database schema.

Gotchas and Tips

Pitfalls

  1. Duplicate Relationship Methods

    • Issue: Self-referential relationships (e.g., parent_id and child_id in the same table) generate duplicate method names like parent() and child().
    • Fix: Manually rename methods in the generated model or extend the generator to handle this case.
  2. Multiple Foreign Keys

    • Issue: Tables with multiple foreign keys to the same table (e.g., polymorphic relationships) may not generate correctly.
    • Fix: Post-process the generated model to add custom relationship methods:
      public function users()
      {
          return $this->morphToMany(User::class, 'userable');
      }
      
  3. Timestamp Detection

    • Issue: The generator may incorrectly set $timestamps = true or false.
    • Fix: Override the shouldUseTimestamps() method or manually adjust the generated models.
  4. Soft Deletes

    • Issue: Soft deletes (deleted_at) are not always detected accurately.
    • Fix: Add the SoftDeletes trait manually or extend the generator to check for the column explicitly.

Debugging Tips

  1. Inspect Generated SQL Enable Laravel’s query logging to debug how the generator reads the database schema:

    DB::enableQueryLog();
    $generator->generateModels(); // Your generator instance
    dd(DB::getQueryLog());
    
  2. Check Table/Column Whitelisting The generator may skip tables or columns not matching expected patterns (e.g., snake_case). Adjust the regex in the generator if needed.

  3. Handle Reserved Keywords If your table/column names conflict with PHP/Laravel keywords (e.g., order, group), escape them in the generated model:

    protected $table = '`order`';
    

Extension Points

  1. Custom Model Naming Override the getModelName() method to enforce naming conventions (e.g., User instead of Users):

    protected function getModelName($table)
    {
        return Str::singular(Str::studly($table));
    }
    
  2. Add Custom Attributes Extend the generator to include additional attributes like $casts or $dates:

    protected function getModelAttributes($table)
    {
        $attributes = parent::getModelAttributes($table);
        $attributes['$casts'] = [
            'created_at' => 'datetime',
            'updated_at' => 'datetime',
        ];
        return $attributes;
    }
    
  3. Support for Custom Relationships Add logic to detect and generate many-to-many or polymorphic relationships:

    public function generateManyToMany($table, $foreignKeys)
    {
        // Custom logic for pivot tables
    }
    
  4. Exclude Tables/Columns Filter out system tables or sensitive columns by overriding:

    protected function shouldSkipTable($table)
    {
        return in_array($table, ['migrations', 'failed_jobs']);
    }
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope