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

mohammedhassan/crud-package

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require mohammedhassan/crud-package
    

    The package auto-registers and installs wendelladriel/laravel-validated-dto as a dependency.

  2. First Command: Generate a basic CRUD scaffold for a Post resource:

    php artisan make:crud Post
    

    This creates:

    • Model (Post.php) + Migration
    • Controller (PostController.php)
    • Service (PostService.php)
    • DTOs (CreatePostDto.php, UpdatePostDto.php)
    • API Resource (PostResource.php)
    • Routes in routes/api.php
  3. Where to Look First:

    • Schema File: Check database/schema/post_schema.php (auto-generated) for validation rules and column definitions.
    • DTOs: Validate input data in app/Dtos/Post/ (e.g., CreatePostDto.php).
    • Service Layer: Business logic in app/Services/PostService.php.
    • Controller: API endpoints in app/Http/Controllers/PostController.php.

Implementation Patterns

Core Workflows

  1. Schema-Driven Development:

    • Define fields in post_schema.php (e.g., title, body):
      return [
          'title' => ['type' => 'string', 'required' => true],
          'body' => ['type' => 'text', 'required' => true],
      ];
      
    • Run php artisan make:crud Post --schema=database/schema/post_schema.php to regenerate files with updated rules.
  2. DTO Validation:

    • Use DTOs for request validation (e.g., CreatePostDto):
      public function rules(): array
      {
          return [
              'title' => 'required|string|max:255',
              'body' => 'required|string',
          ];
      }
      
    • Inject DTOs into the controller:
      public function store(CreatePostDto $dto)
      {
          $this->postService->create($dto);
      }
      
  3. Service Layer Integration:

    • Decouple logic from controllers:
      // PostService.php
      public function create(CreatePostDto $dto)
      {
          return Post::create($dto->toArray());
      }
      
    • Call from controller:
      public function store(CreatePostDto $dto)
      {
          return $this->postService->create($dto);
      }
      
  4. API Resource Routing:

    • Auto-generated routes in routes/api.php:
      Route::apiResource('posts', PostController::class);
      
    • Customize routes with --api-route:
      php artisan make:crud Post --api-route=routes/api/v2.php
      
  5. Testing:

    • Test DTOs, services, and controllers separately:
      // Test DTO validation
      $this->expectException(ValidationException::class);
      CreatePostDto::fromArray([])->validate();
      

Integration Tips

  • Existing Projects:
    • Use --force to overwrite files:
      php artisan make:crud Post --force
      
  • Custom Templates:
    • Override blade templates in resources/views/vendor/crud-package/ (if supported).
  • Event Handling:
    • Extend the service layer to dispatch events (e.g., PostCreated):
      event(new PostCreated($post));
      
  • API Versioning:
    • Group routes by version:
      php artisan make:crud Post --api-route=routes/api/v1/posts.php
      

Gotchas and Tips

Pitfalls

  1. Schema File Path:

    • If --schema is omitted, the package generates a default schema in database/schema/{name}_schema.php.
    • Fix: Explicitly pass the schema path to avoid confusion:
      php artisan make:crud Post --schema=database/schema/post_schema.php
      
  2. DTO Validation Conflicts:

    • DTO rules may override schema definitions if not synchronized.
    • Tip: Regenerate DTOs after schema changes:
      php artisan make:crud Post --schema=database/schema/post_schema.php --force
      
  3. Route Name Collisions:

    • Auto-generated routes (e.g., posts.index) may conflict with existing routes.
    • Solution: Use --api-route to isolate routes or manually adjust Route::apiResource namespaces.
  4. Service Provider Binding:

    • Services are auto-bound to the container. Override bindings in AppServiceProvider if needed:
      $this->app->bind(PostService::class, function ($app) {
          return new CustomPostService();
      });
      
  5. Migration Conflicts:

    • Running make:crud after manual migrations may cause schema mismatches.
    • Tip: Delete and regenerate migrations with --force:
      php artisan make:crud Post --force
      

Debugging

  1. Command Output:

    • Enable verbose mode for detailed logs:
      php artisan make:crud Post -v
      
  2. DTO Validation Errors:

    • Check the errors() method on the DTO instance:
      $dto = CreatePostDto::fromArray($request->all());
      if ($dto->fails()) {
          return response()->json($dto->errors(), 422);
      }
      
  3. Service Layer Issues:

    • Test services in isolation:
      $service = new PostService();
      $this->assertInstanceOf(Post::class, $service->create($dto));
      

Extension Points

  1. Custom DTOs:

    • Extend base DTOs to add logic:
      class CustomCreatePostDto extends CreatePostDto
      {
          public function additionalRules(): array
          {
              return ['slug' => 'required|unique:posts'];
          }
      }
      
  2. Service Decorators:

    • Decorate services for cross-cutting concerns (e.g., logging):
      class LoggedPostService extends PostService
      {
          public function create(CreatePostDto $dto)
          {
              Log::info('Creating post', $dto->toArray());
              return parent::create($dto);
          }
      }
      
  3. Schema Customization:

    • Add dynamic schema logic:
      // In post_schema.php
      return function () {
          return [
              'title' => ['type' => 'string', 'required' => request()->wantsJson()],
          ];
      };
      
  4. API Resource Extensions:

    • Override toArray() in PostResource:
      public function toArray($request)
      {
          return array_merge(parent::toArray($request), [
              'custom_field' => $this->resource->customAttribute,
          ]);
      }
      
  5. Command Customization:

    • Publish and modify the command template:
      php artisan vendor:publish --tag=crud-package-templates
      
    • Edit config/crud-package.php for global defaults (e.g., namespace prefixes).
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