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

Generators Laravel Package

laracasts/generators

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require laracasts/generators
    

    Publish the package assets (if needed):

    php artisan vendor:publish --provider="Laracasts\Generators\GeneratorsServiceProvider"
    
  2. First Use Case Generate a Model + Migration + Controller + Views for a Post resource:

    php artisan generate:model Post -m -c -r
    
    • -m: Creates a migration.
    • -c: Generates a controller.
    • -r: Scaffolds CRUD views (Blade templates).

    Verify the generated files in:

    app/Models/Post.php
    database/migrations/YYYY_MM_DD_create_posts_table.php
    app/Http/Controllers/PostController.php
    resources/views/posts/
    
  3. Where to Look First

    • Documentation: Laracasts Generators Docs (check the README for flags and options).
    • Artisan Commands: Run php artisan to see available generators (e.g., generate:model, generate:controller, generate:middleware).
    • Customization: Override default templates in resources/views/vendor/generators/ (published by the package).

Implementation Patterns

Usage Patterns

  1. Model + Migration Generation Generate a User model with a custom table name and fields:

    php artisan generate:model User -m --table=app_users --fields="name:string,email:string:unique,password:string"
    
    • Schema Awareness: The migration includes the specified fields with correct Laravel schema methods (e.g., string, unique).
  2. Controller Generation Generate a RESTful controller for an existing model:

    php artisan generate:controller PostController --resource --model=Post
    
    • Resourceful Routes: Automatically includes index, store, show, update, destroy methods.
  3. View Scaffolding Generate Blade views for a Product resource:

    php artisan generate:model Product -m -c -r
    
    • Layout Integration: Views extend resources/views/layouts/app.blade.php by default.
    • Form Fields: Uses old() for flash data and includes CSRF tokens.
  4. Middleware Generation Create middleware for role-based access:

    php artisan generate:middleware AdminMiddleware
    
    • Handle Method: Generates a stub for the handle method in app/Http/Middleware/AdminMiddleware.php.
  5. Seeding Data Generate a seeder for Post with sample data:

    php artisan generate:seeder PostSeeder --model=Post
    
    • Factory Integration: Uses Post::factory() if a factory exists.

Workflows

  1. Rapid Prototyping

    • Generate a full CRUD stack in minutes:
      php artisan generate:model BlogPost -m -c -r --fields="title:string,content:text,published:boolean"
      php artisan migrate
      
    • Iterate quickly by regenerating views or controllers as requirements evolve.
  2. API-Only Resources Generate a controller for API endpoints:

    php artisan generate:controller Api/V1/UserController --api --model=User
    
    • API Routes: Automatically registers routes in routes/api.php.
  3. Custom Templates Override default templates by copying files from:

    vendor/laracasts/generators/resources/views/vendor/generators/
    

    to:

    resources/views/vendor/generators/
    

    Example: Customize the model template to add timestamps = false by default.

  4. Integration with Testing Generate a feature test for a controller:

    php artisan generate:test PostControllerTest --controller=PostController
    
    • Test Stubs: Includes assertions for common CRUD actions.

Integration Tips

  1. Laravel Forge/Envoyer

    • Regenerate assets (views, migrations) in staging before deploying:
      php artisan generate:model NewFeature -m -r
      git add .
      git commit -m "Add NewFeature scaffolding"
      
  2. Laravel Nova Generate a Nova resource alongside a model:

    php artisan generate:model Article -m -c -r
    php artisan nova:resource ArticleResource
    
  3. Custom Artisan Commands Extend the package by creating a custom generator:

    // app/Console/Commands/GenerateAdminPanel.php
    use Laracasts\Generators\GeneratorsServiceProvider;
    
    class GenerateAdminPanel extends Command {
        protected $signature = 'generate:admin {name}';
        protected $description = 'Generate an admin panel structure';
    
        public function handle() {
            $this->call('generate:controller', ['name' => 'AdminController', '--api' => true]);
            // Add custom logic...
        }
    }
    
  4. Schema Blueprints Use the --schema flag to generate migrations from an existing database:

    php artisan generate:schema:model User --table=users
    

Gotchas and Tips

Pitfalls

  1. Overwriting Files

    • Regenerating a model/controller without flags may overwrite existing files.
    • Solution: Use --force cautiously or back up files first.
  2. View Namespace Conflicts

    • Custom view paths may conflict with the package’s default resources/views/posts/ structure.
    • Solution: Explicitly set the view path in config/generators.php:
      'view_path' => 'resources/views/custom_posts/',
      
  3. Migration Timestamps

    • By default, migrations include timestamps. To disable:
      php artisan generate:model NoTimestampsModel -m --no-timestamps
      
  4. Route Model Binding

    • Generated controllers assume route model binding. For custom keys:
      php artisan generate:controller PostController --resource --model=Post --primaryKey=id
      
  5. Blade Directives

    • Generated views use @extends and @section. If your layout uses @stack, update the template manually.

Debugging

  1. Artisan Command Errors

    • Check the command signature:
      php artisan generate:model --help
      
    • Common issues:
      • Missing -m flag for migrations.
      • Table name conflicts (e.g., users vs. user).
  2. Template Rendering Issues

    • Clear compiled views:
      php artisan view:clear
      
    • Verify template paths in config/generators.php.
  3. Migration Conflicts

    • If migrations fail due to duplicate columns, use --force (but review changes):
      php artisan generate:model User -m --force
      

Config Quirks

  1. Customizing Field Types Extend the field types in config/generators.php:

    'field_types' => [
        'rich_text' => ['type' => 'text', 'comment' => 'Rich text content'],
    ],
    

    Then use:

    php artisan generate:model Page -m --fields="content:rich_text"
    
  2. Disabling Default Features Disable CRUD views by default:

    'generate_views' => false,
    
  3. Model Namespace Change the default model namespace:

    'model_namespace' => 'App\\Entities',
    

Extension Points

  1. Custom Generators Create a new generator by extending Laracasts\Generators\GeneratorsServiceProvider:

    // app/Providers/AppServiceProvider.php
    use Laracasts\Generators\GeneratorsServiceProvider as BaseGenerators;
    
    class AppServiceProvider extends BaseGenerators {
        public function register() {
            $this->registerGenerator('generate:api-resource', \App\Console\Commands\GenerateApiResource::class);
        }
    }
    
  2. Hooks for Post-Generation Use Laravel events to run logic after generation (e.g., add a policy):

    // app/Providers/EventServiceProvider.php
    protected $listen = [
        'generators.generated' => [
            \App\Listeners\AddPolicyAfterGeneration::class,
        ],
    ];
    
  3. Dynamic Field Generation Override the field parser to add dynamic logic:

    // app/Providers/AppServiceProvider.php
    use Laracasts\Generators\GeneratorsServiceProvider;
    
    class AppServiceProvider extends GeneratorsServiceProvider {
        protected function getFieldTypes() {
            $types = parent::getFieldTypes();
            $types['encrypted'] = ['type' => 'string', 'comment' => 'Encrypted field'];
            return $types;
        }
    }
    
  4. **Localization

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.
anousss007/vigilance
supportpal/eloquent-model
ardenexal/fhir-models
laravel-at/laravel-image-sanitize
romalytar/yammi-audit-log-laravel
ardenexal/fhir-validation
arshaviras/weather-widget
laravel-chronicle/core
sunchayn/nimbus
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