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

rayvenues/eloquent-model-generator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add the package via Composer in development mode:
    composer require rayvenues/eloquent-model-generator --dev
    
  2. Run Migrations: Ensure your database schema is up-to-date with migrations executed.
  3. First Generation: Generate a model for an existing table (e.g., users):
    php artisan ray:generate:model User
    
    This creates a User model in app/Models with App\Models namespace, auto-detecting the users table.

Where to Look First

  • Artisan Command: Check php artisan for the ray:generate:model command and its options.
  • Generated Model: Inspect the output file to understand default field mappings (e.g., id$primaryKey, created_at$timestamps).
  • Configuration: Review the package’s README for advanced options like --table-name or --output-path.

First Use Case

Generate a CRUD-friendly model for a posts table with custom output path:

php artisan ray:generate:model Post --table-name=posts --output-path=Custom/Models

This creates Post.php in app/Custom/Models with Custom\Models namespace.


Implementation Patterns

Core Workflows

  1. Schema-Driven Generation:

    • Use the generator to scaffold models for new tables or legacy databases without manual php artisan make:model.
    • Example: Generate a Reservation model for a reservations table with timestamps and soft deletes:
      php artisan ray:generate:model Reservation --table-name=reservations
      
  2. Team Onboarding:

    • Standardize model generation across a team by documenting a naming convention (e.g., --output-path=Domain/Models).
    • Example: Generate all auth-related models in a Auth/Models directory:
      php artisan ray:generate:model User --output-path=Auth/Models --namespace=App\Auth\Models
      
  3. Integration with Migrations:

    • Pair with php artisan migrate to ensure models are generated for newly created tables.
    • Add a post-migration hook (e.g., in a custom MigrateFresh command) to auto-generate models:
      // app/Console/Commands/MigrateFresh.php
      public function handle() {
          $this->call('migrate:fresh');
          $this->call('ray:generate:model', ['name' => 'User']);
      }
      
  4. Partial Overrides:

    • Generate a base model, then manually extend it for custom logic (e.g., accessors/mutators).
    • Example: Generate Product, then add a custom getFormattedPrice() method.

Advanced Patterns

  1. Dynamic Table Names:

    • Use --table-name to handle pluralization inconsistencies (e.g., role table → Role model):
      php artisan ray:generate:model Role --table-name=role
      
  2. Namespace Organization:

    • Group models by domain (e.g., Admin/Models, Api/Models) for better IDE navigation:
      php artisan ray:generate:model AdminUser --output-path=Admin/Models --namespace=App\Admin\Models
      
  3. Custom Field Mappings:

    • Post-generation, override default field mappings (e.g., slug$fillable):
      // After generation, manually add:
      protected $fillable = ['slug', 'title'];
      
  4. Testing:

    • Use the generator in CI pipelines to ensure schema changes don’t break models.
    • Example GitHub Actions step:
      - run: php artisan ray:generate:model User --table-name=users
      

Gotchas and Tips

Pitfalls

  1. Table Name Mismatches:

    • The generator assumes snake_case tables (e.g., usersUser). If your table is user, use --table-name=user to avoid errors.
    • Debug Tip: Run php artisan ray:generate:model User --debug to see the resolved table name.
  2. Output Path Permissions:

    • If --output-path points to a restricted directory, the command fails silently. Use absolute paths (e.g., /var/www/app/Models) to avoid issues.
    • Fix: Ensure the directory exists and is writable:
      mkdir -p app/Custom/Models && chmod -R 775 app/Custom/Models
      
  3. Namespace Collisions:

    • Generating a model with the same name in a different namespace (e.g., User in App\Models and Admin\Models) can cause IDE confusion.
    • Solution: Use unique prefixes (e.g., AdminUser instead of User).
  4. Soft Deletes/Timestamps:

    • The generator auto-detects created_at, updated_at, and deleted_at columns but doesn’t add use SoftDeletes or HasFactory traits by default.
    • Workaround: Manually add traits post-generation or extend the package to support this.
  5. Foreign Key Handling:

    • The generator does not create relationships (e.g., belongsTo). You’ll need to add these manually or extend the package to support --with-relations.

Debugging

  1. Dry Run:

    • Use --dry-run to preview changes without writing files:
      php artisan ray:generate:model User --dry-run
      
  2. Verbose Output:

    • Add -v or -vv for detailed logs:
      php artisan ray:generate:model User -vv
      
  3. Schema Inspection:

    • Verify the table schema before generation:
      php artisan schema:dump --prune
      

Extension Points

  1. Custom Field Types:

    • Extend the generator to handle custom field types (e.g., JSON columns). Override the generateField() method in a service provider:
      // app/Providers/AppServiceProvider.php
      public function register() {
          $this->app->extend('model-generator', function ($generator) {
              $generator->addFieldType('json', function ($field) {
                  return "protected \${$field['name']};";
              });
              return $generator;
          });
      }
      
  2. Pre/Post-Generation Hooks:

    • Use Laravel’s registering event to modify generated models:
      // app/Providers/EventServiceProvider.php
      protected $listen = [
          'eloquent.model.generated' => [
              'App\Listeners\AddCustomLogicToModel',
          ],
      ];
      
  3. Template Overrides:

    • Replace the default model template by publishing and modifying the package’s views:
      php artisan vendor:publish --tag=model-generator-views
      
    • Edit resources/views/vendor/model-generator/model.stub to customize the output.
  4. Batch Generation:

    • Create a custom command to generate models for multiple tables:
      // app/Console/Commands/GenerateModels.php
      public function handle() {
          $tables = ['users', 'posts', 'roles'];
          foreach ($tables as $table) {
              $this->call('ray:generate:model', [
                  'name' => studly_case($table),
                  '--table-name' => $table,
              ]);
          }
      }
      
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