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

giacomomasseron/laravel-models-generator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation

    composer require giacomomasseron/laravel-models-generator
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="GiacomoMasseron\LaravelModelsGenerator\LaravelModelsGeneratorServiceProvider"
    
  2. First Use Case Generate models for an existing database:

    php artisan models:generate
    

    This will scan your database and create model files in app/Models/ with:

    • Eloquent models
    • Casts (enums, JSON, URI, etc.)
    • Relationships (including polymorphic)
    • UUID/ULID support
  3. Where to Look First

    • Config File: config/models-generator.php (customize paths, naming conventions, or excluded tables).
    • Artisan Commands: php artisan models:generate (core command) and php artisan models:generate:factory (for factories).
    • Generated Output: Check app/Models/ for new files and database/factories/ for factories.

Implementation Patterns

Core Workflows

  1. Generating Models from Scratch

    php artisan models:generate --table=users --path=app/Models/Custom
    
    • Override default output path (--path).
    • Generate a single table (--table) or all tables (default).
  2. Generating Factories

    php artisan models:generate:factory --table=users
    
    • Creates a factory in database/factories/ with fakerized data.
    • Supports --count to generate multiple records for seeding.
  3. Integration with Migrations

    • Use the generated models as a reference to write migrations for new databases.
    • Example: After generating models, manually create a migration for a new table, then regenerate models to auto-update the model.
  4. Customizing Generation

    • Exclude Tables: Add to config/models-generator.php:
      'exclude' => ['migrations', 'failed_jobs'],
      
    • Naming Conventions: Override snake_case to studly_case or custom patterns:
      'naming' => [
          'prefix' => 'App\\Models\\',
          'suffix' => '',
      ],
      
  5. Polymorphic Relationships

    • The generator auto-detects polymorphic columns (e.g., user_id, user_type) and creates:
      public function user(): MorphTo
      {
          return $this->morphTo();
      }
      
  6. UUID/ULID Support

    • If a column is named *_id and has a type like uuid or char(36), it casts to HasUuid or HasUlid:
      protected $casts = [
          'id' => Uuid::class,
      ];
      
  7. Enum and JSON Casting

    • Detects enum columns and casts to Enum:
      protected $casts = [
          'status' => Status::class, // Auto-generated enum class
      ];
      
    - JSON columns are cast to `array`:
      ```php
      protected $casts = [
          'metadata' => 'array',
      ];
    
  8. Seeding with Generated Factories

    // database/seeders/DatabaseSeeder.php
    public function run()
    {
        \App\Models\User::factory()->count(10)->create();
    }
    

Gotchas and Tips

Pitfalls

  1. Overwriting Existing Models

    • The generator skips tables with existing models by default.
    • Force overwrite with --force:
      php artisan models:generate --force
      
    • Tip: Use --dry-run first to preview changes:
      php artisan models:generate --dry-run
      
  2. Polymorphic Ambiguity

    • If two tables have columns like user_id and post_id, the generator may misidentify relationships.
    • Fix: Manually adjust the generated morphTo() calls or rename columns.
  3. UUID/ULID Misconfiguration

    • The generator assumes uuid/ulid columns are for primary keys or foreign keys.
    • Gotcha: If you have a non-key UUID column (e.g., external_id), it may incorrectly cast to HasUuid.
    • Fix: Add a comment in the migration or manually adjust the model.
  4. Enum Generation Quirks

    • Enums are generated as PHP 8.1+ enum classes in app/Enums/.
    • Issue: If your project uses older PHP, enums won’t work.
    • Fix: Downgrade to string casts or use a polyfill.
  5. SQLite-Specific Issues

    • SQLite doesn’t support all data types (e.g., enum). The generator may fail or produce suboptimal casts.
    • Tip: Use --skip-types to ignore type casting for SQLite.
  6. Factory Fakerization

    • Factories use Faker defaults, which may not match your app’s data.
    • Tip: Manually edit generated factories to include custom rules:
      ->state(fn (array $attributes) => [
          'status' => fake()->randomElement(['active', 'inactive']),
      ])
      

Debugging

  1. Verbose Output Enable debug mode to see SQL queries and generation steps:

    php artisan models:generate --verbose
    
  2. Log File Check storage/logs/laravel.log for errors during generation.

  3. Doctrine DBAL Issues If using unsupported drivers, install the Doctrine DBAL extension:

    composer require doctrine/dbal
    

Extension Points

  1. Custom Model Templates Override the default Blade template by publishing and modifying:

    php artisan vendor:publish --tag=models-generator-templates
    
    • Edit resources/views/vendor/models-generator/model.stub.
  2. Post-Generation Hooks Use Laravel’s generated:model event to run custom logic after generation:

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        'generated:model' => [
            \App\Listeners\PostModelGeneration::class,
        ],
    ];
    
  3. Dynamic Configuration Override config per environment by publishing the config and modifying:

    // config/models-generator.php (local override)
    'naming' => [
        'prefix' => env('MODEL_NAMESPACE', 'App\Models\\'),
    ],
    
  4. Skipping Tables via Code Dynamically exclude tables in a service provider:

    $generator->exclude(['temp_tables', 'logs']);
    

Pro Tips

  • Pair with Laravel Jetstream/Sanctum: Generate models first, then scaffold auth scaffolding to avoid manual model creation.
  • Use with Laravel Breeze: Generate models for your database, then integrate with Breeze’s controllers.
  • CI/CD Integration: Add to your deployment pipeline to keep models in sync with the database schema:
    # .github/workflows/deploy.yml
    - run: php artisan models:generate --force
    
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