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

Crud Generator Laravel Package

suryahadiningrat/crud-generator

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation

    composer require suryahadiningrat/crud-generator
    

    Publish the config file (if available):

    php artisan vendor:publish --provider="Suryahadiningrat\CrudGenerator\CrudGeneratorServiceProvider"
    
  2. Basic Usage Generate a CRUD for an existing model (e.g., User):

    php artisan crud:generate User
    

    This creates:

    • Controller (app/Http/Controllers/UserController.php)
    • Views (in resources/views/crud/user/)
    • Routes (if configured to auto-register)
  3. Where to Look First

    • Config File: Check config/crud-generator.php for customization (e.g., view paths, resource naming).
    • Generator Class: Inspect Suryahadiningrat\CrudGenerator\Generators\CrudGenerator for logic.
    • Blade Templates: Default templates are in vendor/suryahadiningrat/crud-generator/resources/views/.
  4. First Use Case Generate a CRUD for a Product model with custom fields:

    php artisan crud:generate Product --fields="name:string,price:decimal,stock:int"
    

    Verify the generated controller and views for basic CRUD operations (index, create, store, edit, update, destroy).


Implementation Patterns

Core Workflows

  1. Model-Based Generation

    • Default Fields: Auto-detects model properties (e.g., name, email for User).
    • Custom Fields: Override defaults via CLI flags (e.g., --fields).
    • Relationships: Supports basic relationships (e.g., --with-relations="posts" for a User model).
  2. View Customization

    • Override Templates: Copy default Blade templates from vendor/ to resources/views/crud/ to customize.
    • Partial Templates: Extend partials (e.g., _form.blade.php) for reusable components.
    • Layouts: Use Laravel’s @extends in generated views to integrate with your app’s layout.
  3. Controller Integration

    • Base Controller: Extend the generated controller to add business logic:
      namespace App\Http\Controllers;
      use Suryahadiningrat\CrudGenerator\Controllers\CrudController;
      
      class ProductController extends CrudController
      {
          public function store(Request $request)
          {
              // Custom validation/logic before parent::store()
              return parent::store($request);
          }
      }
      
    • Resource Routes: Manually add routes in routes/web.php if auto-registration is disabled:
      Route::resource('products', \App\Http\Controllers\ProductController::class);
      
  4. API Support

    • Generate API-specific CRUD by passing --api flag:
      php artisan crud:generate Post --api
      
    • Customize API responses by overriding the generated controller’s methods (e.g., index(), show()).
  5. Testing

    • Unit Tests: Test generated controllers by mocking dependencies (e.g., Product::class).
    • Feature Tests: Use Laravel’s actingAs() and followRedirects() to test CRUD flows.

Integration Tips

  • Form Requests: Pair with Laravel’s Form Requests for validation:
    php artisan make:request StoreProductRequest
    
    Update the generated controller to use the request class.
  • Authorization: Use Laravel’s gates/policies in the controller’s methods (e.g., authorize('update', $model)).
  • Events: Attach events (e.g., created, updated) in the model to trigger side effects:
    class Product extends Model
    {
        protected $dispatchesEvents = [
            'created' => ProductCreated::class,
        ];
    }
    
  • Localization: Override generated views to support localization (e.g., __('crud.labels.name')).

Gotchas and Tips

Pitfalls

  1. Config Overrides

    • Issue: Custom config settings (e.g., view_path) may not apply if the package lacks a publishable config.
    • Fix: Manually set the config in config/app.php or extend the service provider:
      public function boot()
      {
          $this->app['crud-generator']->setViewPath(resource_path('views/custom-crud'));
      }
      
  2. Namespace Conflicts

    • Issue: Generated controllers may conflict with existing ones if namespaces aren’t adjusted.
    • Fix: Use --namespace flag or manually rename the controller:
      php artisan crud:generate Product --namespace="Admin"
      
  3. Relationship Handling

    • Issue: Complex relationships (e.g., polymorphic, many-to-many) may not render correctly in forms.
    • Fix: Customize the _form.blade.php template or extend the generator class to handle specific cases.
  4. Route Caching

    • Issue: Auto-registered routes may not reflect changes until cache is cleared:
      php artisan route:clear
      
    • Fix: Disable auto-registration in config and manually define routes.
  5. Blade Template Caching

    • Issue: Changes to Blade templates may not update until cache is cleared:
      php artisan view:clear
      

Debugging

  • Generator Logic: Add debug logs in Suryahadiningrat\CrudGenerator\Generators\CrudGenerator:
    \Log::debug('Generating CRUD for: ', [$modelName, $fields]);
    
  • View Rendering: Check for missing variables in generated views by adding @dump($model) or @dd($errors).
  • Route Debugging: List routes to verify auto-registration:
    php artisan route:list
    

Extension Points

  1. Custom Generators Extend the base generator to add support for new features (e.g., soft deletes, activity logs):

    namespace App\Generators;
    use Suryahadiningrat\CrudGenerator\Generators\CrudGenerator as BaseGenerator;
    
    class CustomCrudGenerator extends BaseGenerator
    {
        protected function generateController()
        {
            // Add custom logic (e.g., soft delete methods)
            parent::generateController();
        }
    }
    

    Register the custom generator in a service provider.

  2. Dynamic Field Mapping Override field type handling in the generator to support custom database columns (e.g., JSON, enum):

    protected function mapFieldType($field)
    {
        if (str_contains($field, 'json')) {
            return 'textarea';
        }
        return parent::mapFieldType($field);
    }
    
  3. Event Hooks Listen for CRUD events to inject logic (e.g., logging, notifications):

    // In EventServiceProvider
    protected $listen = [
        \Suryahadiningrat\CrudGenerator\Events\CrudGenerated::class => [
            \App\Listeners\LogCrudGeneration::class,
        ],
    ];
    
  4. Template Inheritance Use Laravel Mixins or Blade directives to extend generated views dynamically:

    // In AppServiceProvider
    Blade::directive('crudExtend', function ($expression) {
        return "<?php echo \$__env->make('crud._extensions.$expression', []); ?>";
    });
    

    Then in a generated view:

    @crudExtend('custom-form-fields')
    

Tips

  • Backup Generated Files: Use .gitignore to exclude generated files or commit them to version control for reproducibility.
  • Document Customizations: Add comments in generated files to track modifications:
    // Custom: Added validation for 'price' field
    $validator->rules['price'] = 'required|numeric|min:0';
    
  • Leverage Laravel Mix: Compile assets for generated views using Laravel Mix or Vite.
  • Performance: For large models, generate CRUD incrementally (e.g., first create the controller, then views).
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.
monarobase/country-list
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity