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

Eloquent Model Generator Laravel Package

user11001/eloquent-model-generator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require --dev pepijnolivier/eloquent-model-generator
    

    Add the service provider to config/app.php (if not auto-discovered):

    'providers' => [
        // ...
        PepijnOlivier\EloquentModelGenerator\EloquentModelGeneratorServiceProvider::class,
    ],
    
  2. Publish Config (Optional)

    php artisan vendor:publish --provider="PepijnOlivier\EloquentModelGenerator\EloquentModelGeneratorServiceProvider" --tag="config"
    

    Configure paths, naming conventions, and generators in config/eloquent-model-generator.php.

  3. First Generation

    php artisan model:generate
    

    This generates models for all tables in your database. Run with --table=users to target a specific table.


Where to Look First

  • Config File: config/eloquent-model-generator.php – Customize naming, paths, and generator behavior.
  • Artisan Commands:
    • model:generate – Generate models for all tables.
    • model:generate:table – Generate a model for a specific table.
    • model:generate:relation – Generate relations for an existing model.
  • Generators Directory: config/eloquent-model-generator.php defines where custom generators are stored (default: app/Generators).

First Use Case: Scaffold a New Model

  1. Add a Table to Your Database Create a posts table with columns like id, title, body, and user_id.

  2. Generate the Model

    php artisan model:generate:table posts
    

    This creates:

    • app/Models/Post.php (with fillable fields, casts, and timestamps).
    • A user() relation method (if user_id exists and references users table).
  3. Use the Model

    use App\Models\Post;
    
    $posts = Post::with('user')->get(); // Automatically resolves the relation.
    

Implementation Patterns

Core Workflows

1. Generating Models from Scratch

  • Full Schema Sync:
    php artisan model:generate
    
    Generates models for all tables, including relations (e.g., belongsTo, hasMany).
  • Selective Generation:
    php artisan model:generate:table orders --relations
    
    Generates only the orders model with relations.

2. Incremental Updates

  • After adding a column (e.g., status to posts), regenerate the model:
    php artisan model:generate:table posts
    
    The generator detects new columns and updates the model.

3. Customizing Relations

  • Override Relation Logic: Create a custom generator (e.g., app/Generators/CustomPostGenerator.php) extending PepijnOlivier\EloquentModelGenerator\Generators\ModelGenerator.
    public function generateRelation($relationName, $foreignKey, $localKey, $model)
    {
        if ($relationName === 'user') {
            return $model->belongsTo(User::class, 'user_id', 'id')->withDefault();
        }
        return parent::generateRelation($relationName, $foreignKey, $localKey, $model);
    }
    
  • Update config to use your generator:
    'generators' => [
        'App\\Generators\\CustomPostGenerator',
    ],
    

4. Handling Complex Schemas

  • Polymorphic Relations: The generator auto-detects polymorphic columns (e.g., imageable_id + imageable_type). Customize via config:
    'polymorphic' => [
        'columns' => ['imageable_id', 'imageable_type'],
    ],
    
  • Many-to-Many: For pivot tables (e.g., post_tag), generate models with belongsToMany:
    php artisan model:generate:table post_tag
    
    Then manually define the relation in the parent model (e.g., Post.php):
    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'post_tag');
    }
    

5. Integration with Laravel Features

  • Observers/Events: After generation, add observers to app/Providers/AppServiceProvider:
    Post::observe(PostObserver::class);
    
  • API Resources: Generate a resource alongside models using a post-generation hook or a separate package like laravel-shift/api-resource-generator.

Integration Tips

  1. Version Control

    • Exclude generated files from Git (add to .gitignore):
      /app/Models/*
      
    • Use a post-generate script to commit changes:
      php artisan model:generate && git add app/Models && git commit -m "chore: update models"
      
  2. Testing

    • Mock the generator in tests:
      $this->partialMock(PepijnOlivier\EloquentModelGenerator\EloquentModelGenerator::class, ['generateModel']);
      
    • Test relation generation with a temporary database:
      $this->artisan('model:generate:table', ['table' => 'posts'])->assertExitCode(0);
      
  3. CI/CD

    • Run generation in CI to ensure models stay in sync with the schema:
      # .github/workflows/generate-models.yml
      jobs:
        generate-models:
          runs-on: ubuntu-latest
          steps:
            - uses: actions/checkout@v4
            - uses: actions/setup-php@v3
            - run: composer install
            - run: php artisan model:generate
            - run: git diff --exit-code
      

Gotchas and Tips

Pitfalls

  1. Overwriting Existing Models

    • The generator overwrites existing files by default. To avoid accidents:
      • Use --dry-run to preview changes:
        php artisan model:generate --dry-run
        
      • Backup models before generation or use --backup (if supported in future versions).
  2. Circular Relations

    • If tables have circular references (e.g., User has Post, Post has User), the generator may produce ambiguous relation names. Resolve by:
      • Customizing relation names in config:
        'relations' => [
            'user' => 'author',
        ],
        
      • Manually editing the generated model.
  3. Reserved Keywords

    • Column names like class, table, or created_at may cause syntax errors. Rename them in the database or use config to ignore:
      'ignored_columns' => ['class', 'table'],
      
  4. Soft Deletes

    • The generator auto-detects deleted_at columns but doesn’t enable soft deletes by default. Add this to your model:
      use Illuminate\Database\Eloquent\SoftDeletes;
      
      class Post extends Model
      {
          use SoftDeletes;
          protected $dates = ['deleted_at'];
      }
      
  5. Custom Primary Keys

    • If a table uses a non-integer primary key (e.g., uuid), the generator may not handle it correctly. Override the primary key in config:
      'primary_key' => 'uuid',
      

Debugging

  1. Verbose Output Enable debug mode in config:

    'debug' => true,
    

    Or run with:

    php artisan model:generate --verbose
    
  2. Log Generation Check storage/logs/laravel.log for errors during generation. Example log entry:

    [2025-11-13 12:00:00] local.INFO: Generating model for table [posts]...
    [2025-11-13 12:00:01] local.ERROR: Failed to generate relation [user]: Column [user_id] not found.
    
  3. Manual Relation Fixes If relations are misgenerated, manually correct them in the model:

    // Wrong (generated):
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'user_id');
    }
    // Correct:
    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
    

Tips

  1. Naming Conventions Customize model/class naming in config:

    'naming' => [
        'model' => 'PostModel', // Default: Post
        'class' => 'App\\Models\\PostModel',
    ],
    
  2. Excluding Tables Ignore specific tables (e.g., migrations, failed_jobs):

    'ignored_tables' => ['
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky