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

Core Laravel Package

cnd-api-maker/core

Laravel package for building and scaffolding API endpoints with CND API Maker. Provides core helpers and structure to generate controllers, routes, and resources, speeding up common CRUD API development and standardizing patterns across projects.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require coundia/cnd-api-maker-core
    

    Verify the package is auto-discovered in config/app.php under providers. If not, manually add:

    Coundia\ApiMaker\Core\ApiMakerServiceProvider::class,
    
  2. Publish Configuration (if available):

    php artisan vendor:publish --provider="Coundia\ApiMaker\Core\ApiMakerServiceProvider" --tag="config"
    

    (Note: Check if the package includes a config file; if not, proceed without.)

  3. First Use Case: Generate a basic CRUD API for an existing Eloquent model (e.g., User). (Assuming the package provides an Artisan command—verify with php artisan list.)

    php artisan make:api User
    
    • This should create:
      • Controller (app/Http/Controllers/Api/UserController.php).
      • Request classes for validation (app/Http/Requests/Api/UserRequest.php).
      • Routes in routes/api.php (e.g., GET|POST|PUT|DELETE /users).
      • (Check documentation for exact output; adjust based on actual package behavior.)
  4. Test the API:

    php artisan serve
    

    Send a test request to http://localhost:8000/api/users (e.g., using Postman or curl).


Implementation Patterns

Usage Patterns

  1. Standard CRUD Workflow:

    • Create: Use POST /users with a validated request body.
      {
        "name": "John Doe",
        "email": "[email protected]"
      }
      
    • Read: Fetch all users with GET /users or a single user with GET /users/{id}.
    • Update: Send PUT /users/{id} with updated data.
    • Delete: Use DELETE /users/{id}.
  2. Request Validation: The package likely auto-generates request classes (e.g., StoreUserRequest, UpdateUserRequest) with validation rules. Example rules (check generated file):

    public function rules()
    {
        return [
            'name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
        ];
    }
    

    Extend these classes for custom validation:

    public function rules()
    {
        return array_merge(parent::rules(), [
            'age' => 'nullable|integer|min:18',
        ]);
    }
    
  3. Response Formatting: The package may use Laravel’s API Resources or return raw JSON. Example response:

    {
        "data": {
            "id": 1,
            "name": "John Doe",
            "email": "[email protected]",
            "created_at": "2023-01-01T00:00:00.000000Z"
        }
    }
    

    Customize responses by overriding the controller’s show() or store() methods.

  4. Error Handling: The package should return standardized error responses (e.g., 422 Unprocessable Entity for validation errors):

    {
        "message": "The given data was invalid.",
        "errors": {
            "email": ["The email field is required."]
        }
    }
    

Workflows

  1. Adding a New API:

    • Run the generator command for a new model:
      php artisan make:api Product
      
    • Customize the controller, requests, or routes as needed.
  2. Extending Functionality:

    • Add custom methods to the controller (e.g., public function bulkDelete()).
    • Register additional routes in routes/api.php:
      Route::delete('/users/bulk', [UserController::class, 'bulkDelete']);
      
  3. Testing: Use Laravel’s testing tools to verify generated APIs:

    public function test_create_user()
    {
        $response = $this->postJson('/api/users', [
            'name' => 'Test User',
            'email' => '[email protected]',
        ]);
        $response->assertCreated();
    }
    

Integration Tips

  1. Authentication: Protect generated APIs with Laravel’s auth middleware (e.g., auth:api):

    Route::middleware('auth:api')->group(function () {
        Route::apiResource('users', UserController::class);
    });
    
  2. Pagination: Enable pagination in the controller:

    public function index()
    {
        return User::paginate(15);
    }
    
  3. API Versioning: Use Laravel’s route grouping for versioning:

    Route::prefix('v1')->group(function () {
        Route::apiResource('users', UserController::class);
    });
    
  4. Documentation: Generate OpenAPI/Swagger docs using darkaonline/l5-swagger and annotate generated controllers:

    /**
     * @OA\Get(
     *     path="/api/users",
     *     summary="Get all users",
     *     @OA\Response(response="200", description="Successful operation")
     * )
     */
    public function index()
    

Gotchas and Tips

Pitfalls

  1. Route Conflicts:

    • The package may generate routes that clash with existing ones (e.g., /users vs. /admin/users).
    • Fix: Manually adjust routes in routes/api.php or use route prefixes:
      Route::prefix('api/v1')->apiResource('users', UserController::class);
      
  2. Validation Overrides:

    • Auto-generated validation rules may not match your model’s database constraints.
    • Fix: Extend the request class and override rules():
      public function rules()
      {
          return [
              'email' => 'required|email|unique:users,email,'.$this->user->id,
          ];
      }
      
  3. Missing Middleware:

    • Generated APIs might lack CORS, rate limiting, or logging middleware.
    • Fix: Apply middleware globally in app/Http/Kernel.php or per-route:
      Route::middleware(['cors', 'throttle:60'])->apiResource('users', UserController::class);
      
  4. Database Relationships:

    • The package may not handle nested resources (e.g., users/{user}/posts).
    • Fix: Manually define sub-resources or use Laravel’s apiResource with nested routes.
  5. Testing Challenges:

    • Generated code can make tests brittle (e.g., route changes break tests).
    • Fix: Test behavior, not implementation. Use trait-based testing:
      public function test_user_creation()
      {
          $this->actingAs($user)
               ->postJson('/api/users', ['name' => 'Test'])
               ->assertCreated();
      }
      

Debugging

  1. Log Generated Code: Temporarily add logging to the package’s service provider to see what it generates:

    public function boot()
    {
        \Log::info('Generated routes:', [
            \Route::getRoutes()->getRoutes()
        ]);
    }
    
  2. Check Route Cache: Clear cached routes if changes aren’t reflecting:

    php artisan route:clear
    php artisan config:clear
    
  3. Validate Requests Manually: If validation fails unexpectedly, test the request class directly:

    $request = new StoreUserRequest();
    $validator = \Validator::make($request->all(), $request->rules());
    

Configuration Quirks

  1. No Config File: If the package lacks a config file, hardcode settings in the service provider or environment variables.

  2. Default Naming Conventions: The package may use plural route names (e.g., /users) even if your model is singular (User). Fix: Override the route name in the controller:

    public function __construct()
    {
        $this->resourceName = 'user'; // Singular route
    }
    
  3. Eloquent Model Assumptions: The package likely expects Eloquent models with specific naming (e.g., User for /users). Fix: Use a trait or interface to standardize model naming.

Extension Points

  1. Custom Generators: Extend the package’s generator logic by publishing and modifying its templates:

    php artisan vendor:publish --tag="api-maker-views"
    

    (Note: Verify if the package supports this; if not, fork and modify.)

  2. Hooks for Post-Generation: Add events or listeners to run code after API generation (e.g., seed data, run migrations):

    \Event::listen('api.maker.generated', function ($apiName) {
        \Log::info("Generated API for $apiName
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle