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

Generate Crud Laravel Package

codebider/generate-crud

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require codebider/generate-crud
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Codebider\GenerateCrud\GenerateCrudServiceProvider"
    
  2. First Use Case: Generate a basic CRUD for a Post model with fields:

    php artisan crud:generate
    

    Follow prompts to define:

    • Model name (Post).
    • Fields (e.g., title:string, content:text, published:boolean).
    • Optional: Relationships (e.g., belongsTo:User).
  3. Where to Look First:

    • Config File: config/crud.php (customize paths, editor, or default fields).
    • Generated Files: Check app/Models/, database/migrations/, app/Http/Controllers/, and resources/views/ for auto-generated files.
    • Artisan Command: Run php artisan crud:generate --help for CLI options.

Implementation Patterns

Usage Patterns

  1. Interactive Workflow:

    • Use the default interactive mode for ad-hoc CRUD generation:
      php artisan crud:generate
      
    • Define fields dynamically (e.g., name:string|required, price:decimal:8,2).
  2. Non-Interactive Mode (CI/CD):

    • Pass arguments directly for automation:
      php artisan crud:generate Post --fields="title:string,content:text" --relationships="belongsTo:User"
      
    • Useful for pipelines or repeatable setups.
  3. Custom Templates:

    • Override default Blade views by placing custom templates in resources/views/vendor/crud/.
    • Example: Modify index.blade.php to add custom columns or buttons.
  4. Integration with Existing Code:

    • Models: Extend generated models to add custom accessors/mutators:
      // app/Models/Post.php
      public function getFormattedTitleAttribute()
      {
          return strtoupper($this->title);
      }
      
    • Controllers: Override methods in app/Http/Controllers/PostController:
      public function store(Request $request)
      {
          $request->merge(['slug' => Str::slug($request->title)]);
          return parent::store($request);
      }
      
    • Routes: Extend generated routes in routes/web.php:
      Route::prefix('admin')->group(function () {
          Route::resource('posts', PostController::class);
      });
      
  5. Relationship Handling:

    • Define relationships during generation (e.g., hasMany:Comment).
    • Post-generation, manually add inverse relationships in related models:
      // app/Models/Comment.php
      public function post()
      {
          return $this->belongsTo(Post::class);
      }
      
  6. Validation Rules:

    • Customize validation by overriding the rules() method in the controller:
      protected function rules()
      {
          return [
              'title' => 'required|string|max:255|unique:posts',
              'content' => 'required|string|min:10',
          ];
      }
      
  7. API Resources:

    • For API endpoints, pair with Laravel’s API Resources:
      php artisan make:resource PostResource
      
      Then update the PostController to use the resource.

Workflows

  1. Rapid Prototyping:

    • Generate a CRUD skeleton, then iteratively refine views/controllers.
    • Example:
      php artisan crud:generate Product --fields="name:string,price:decimal:8,2,stock:integer"
      
  2. Team Collaboration:

    • Use non-interactive mode in CI to ensure consistency:
      php artisan crud:generate User --fields="email:string|email|unique,name:string" --relationships="hasMany:Post"
      
    • Document custom fields/relationships in a CRUD_SPEC.md file.
  3. Legacy System Integration:

    • Generate a CRUD for an existing table:
      php artisan crud:generate --table=legacy_users
      
    • Manually adjust the migration if needed (e.g., add indexes).
  4. Multi-Tenant Apps:

    • Extend the controller to add tenant logic:
      public function index()
      {
          $this->authorize('view', Tenant::class);
          return parent::index()->where('tenant_id', auth()->tenant()->id);
      }
      

Integration Tips

  1. Form Requests:

    • Generate a dedicated FormRequest for validation:
      php artisan make:request StorePostRequest
      
    • Update the controller to use it:
      public function store(StorePostRequest $request)
      {
          return parent::store($request);
      }
      
  2. Policy Integration:

    • Attach policies to generated controllers:
      php artisan make:policy PostPolicy --model=Post
      
    • Update the controller constructor:
      public function __construct()
      {
          $this->authorizeResource(Post::class, 'post');
      }
      
  3. Testing:

    • Use Laravel’s testing helpers to assert CRUD functionality:
      public function test_crud_operations()
      {
          $response = $this->get('/posts');
          $response->assertStatus(200);
      
          $this->post('/posts', ['title' => 'Test', 'content' => 'Body'])
               ->assertRedirect();
      }
      
  4. Localization:

    • Override default labels in language files:
      // resources/lang/en/crud.php
      return [
          'posts' => [
              'title' => 'Blog Title',
              'content' => 'Article Content',
          ],
      ];
      
    • Update the view to use the new labels:
      <x-input label="{{ __('crud.posts.title') }}" />
      
  5. File Uploads:

    • Add file fields during generation (e.g., image:file).
    • Extend the controller to handle uploads:
      protected function store(Request $request)
      {
          $data = $request->except('image');
          if ($request->hasFile('image')) {
              $data['image_path'] = $request->file('image')->store('posts');
          }
          return parent::store($data);
      }
      

Gotchas and Tips

Pitfalls

  1. Migration Conflicts:

    • If the table already exists, the generator may fail. Use --force to overwrite:
      php artisan crud:generate --force
      
    • Tip: Always back up your database before running migrations.
  2. Field Name Collisions:

    • Laravel’s $fillable and $casts may conflict with custom methods. Rename generated methods:
      // Avoid naming a method `price` if `price` is a field.
      public function getPriceInDollarsAttribute()
      {
          return '$' . $this->price;
      }
      
  3. Relationship Sync Issues:

    • If you add a relationship post-generation, manually update the inverse relationship in the related model to avoid hasOne/belongsTo mismatches.
  4. View Overrides:

    • Custom templates in resources/views/vendor/crud/ must match the generator’s expected structure. Use php artisan crud:generate --dry-run to preview the expected files.
  5. Editor Integration:

    • The --edit flag uses the editor defined in config/editor.php. Ensure your system’s EDITOR environment variable matches (e.g., export EDITOR="code --wait" for VSCode).
  6. Soft Deletes:

    • The generator does not enable soft deletes by default. Add it manually:
      php artisan make:model Post -m --softDeletes
      
      Then regenerate the CRUD or update the model/controller manually.
  7. Timestamps:

    • If you disable timestamps in the migration, ensure the model’s $dates property is updated to avoid created_at/updated_at errors.

Debugging

  1. Dry Run:

    • Preview generated files without saving:
      php artisan crud:generate --dry-run
      
    • Check the output for errors or unexpected templates.
  2. Log Output:

    • Enable verbose logging for troubleshooting:
      php artisan crud:generate --verbose
      
  3. Manual Overrides:

    • If generation fails, manually create the files and merge changes:
      touch app/Models/Post.php
      php artisan crud:generate --skip-model
      
  4. Database Errors:

    • If migrations fail, check the generated SQL in the migration file. Common issues:
      • Missing foreign key constraints.
      • Incorrect column types (e.g., decimal precision/scale).
    • Fix: Edit the migration file, then
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.
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
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle