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

Crudpackage Laravel Package

harryes/crudpackage

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to Begin

  1. Installation:

    composer require harryes/crudpackage
    

    Publish the package config (if needed) with:

    php artisan vendor:publish --provider="Harryes\CrudPackage\CrudPackageServiceProvider"
    
  2. First Command: Generate a basic CRUD structure for a User model with essential fields:

    php artisan crud:generate User --columns=name:string,email:string,age:integer
    

    This creates:

    • Model (app/Models/User.php)
    • Migration (database/migrations/..._create_users_table.php)
    • Controller (app/Http/Controllers/UserController.php)
    • Resource (app/Http/Resources/UserResource.php)
    • Routes (routes/api.php)
  3. Where to Look First:

    • Generated Files: Check app/Http/Controllers/ for the controller logic.
    • Routes: Inspect routes/api.php for API endpoints (e.g., /users, /users/{id}).
    • Resource: Review app/Http/Resources/ for API response formatting.
    • Config: If published, check config/crudpackage.php for customization options.

Implementation Patterns

Core Workflows

  1. Rapid API Scaffolding:

    • Use the command to bootstrap a new API endpoint in minutes. Example:
      php artisan crud:generate Product --columns=name:string,price:decimal,stock:integer,description:text
      
    • Automatically generates:
      • index, store, show, update, destroy methods in the controller.
      • Form request validation (if enabled in config).
  2. Integration with Existing Code:

    • Extend Controllers: Override generated methods in the controller:
      // app/Http/Controllers/UserController.php
      public function store(Request $request)
      {
          // Custom logic before saving
          $validated = $this->validate($request);
          $user = User::create($validated);
      
          // Custom logic after saving
          return (new UserResource($user))->response()->setStatusCode(201);
      }
      
    • Custom Resources: Extend the generated resource:
      // app/Http/Resources/UserResource.php
      public function toArray($request)
      {
          return array_merge(parent::toArray($request), [
              'custom_field' => $this->whenLoaded('custom_field'),
          ]);
      }
      
  3. Dynamic Column Handling:

    • Add new columns to the migration and update the command:
      php artisan crud:generate Post --columns=title:string,content:text,is_published:boolean,published_at:timestamp
      
    • The package dynamically updates the model, controller, and resource.
  4. API Versioning:

    • Group routes by version in routes/api.php:
      Route::prefix('v1')->group(function () {
          Route::apiResource('users', UserController::class);
      });
      
  5. Testing:

    • Use Laravel’s built-in testing tools to verify CRUD operations:
      public function test_create_user()
      {
          $response = $this->postJson('/api/v1/users', [
              'name' => 'Test User',
              'email' => 'test@example.com',
              'age' => 30
          ]);
          $response->assertStatus(201);
      }
      

Gotchas and Tips

Pitfalls and Debugging

  1. Column Type Mismatches:

    • Ensure column types in the --columns parameter match Laravel’s migration syntax. For example:
      • Use timestamp instead of datetime for timestamps.
      • Use decimal:8,2 for precise decimal values.
    • Fix: Regenerate the CRUD with corrected types or manually edit the migration.
  2. Route Conflicts:

    • If you generate multiple CRUDs with overlapping routes (e.g., users and admins), Laravel may throw a RouteAlreadyRegistered error.
    • Fix: Use route namespaces or prefixes:
      Route::prefix('admin')->name('admin.')->apiResource('users', AdminUserController::class);
      
  3. Soft Deletes:

    • The softDeletes type adds deleted_at to the migration but doesn’t enable soft deletes in the model by default.
    • Fix: Manually add use SoftDeletes; and $dates = ['deleted_at']; to the model.
  4. Validation Rules:

    • The package doesn’t generate custom validation rules by default. Rules like email:required|email are hardcoded.
    • Fix: Extend the generated StoreUserRequest or UpdateUserRequest:
      public function rules()
      {
          return array_merge(parent::rules(), [
              'age' => 'nullable|integer|min:18',
          ]);
      }
      
  5. Foreign Key Constraints:

    • The package doesn’t handle relationships (e.g., belongsTo, hasMany) automatically.
    • Fix: Manually define relationships in the model and update the migration:
      // Model
      public function posts()
      {
          return $this->hasMany(Post::class);
      }
      
      // Migration
      $table->foreignId('user_id')->constrained()->onDelete('cascade');
      
  6. Config Overrides:

    • Customize the package behavior via config/crudpackage.php (published after installation).
    • Example: Disable resource generation:
      'generate_resource' => false,
      

Extension Points

  1. Custom Templates:

    • Override the package’s Blade templates (if used) by publishing and modifying:
      php artisan vendor:publish --tag=crudpackage-views
      
  2. Event Listeners:

    • Attach listeners to model events (e.g., created, deleted) in the controller or a service:
      // app/Providers/EventServiceProvider.php
      protected $listen = [
          'Harryes\CrudPackage\Models\User' => [
              'created' => [\App\Listeners\LogUserCreation::class],
          ],
      ];
      
  3. API Middleware:

    • Apply middleware to specific routes:
      Route::middleware(['auth:sanctum'])->apiResource('users', UserController::class);
      
  4. Testing Helpers:

    • Create a trait for reusable CRUD tests:
      // tests/Traits/CrudTestTrait.php
      public function assertCrudOperations()
      {
          $this->assertRouteExists('users.index');
          $this->assertRouteExists('users.store');
          // Add more assertions...
      }
      
  5. Dynamic Permissions:

    • Integrate with packages like spatie/laravel-permission to restrict CRUD actions:
      public function index()
      {
          $this->authorize('view', User::class);
          return UserResource::collection(User::all());
      }
      
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.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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