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.
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,
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.)
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
app/Http/Controllers/Api/UserController.php).app/Http/Requests/Api/UserRequest.php).routes/api.php (e.g., GET|POST|PUT|DELETE /users).Test the API:
php artisan serve
Send a test request to http://localhost:8000/api/users (e.g., using Postman or curl).
Standard CRUD Workflow:
POST /users with a validated request body.
{
"name": "John Doe",
"email": "[email protected]"
}
GET /users or a single user with GET /users/{id}.PUT /users/{id} with updated data.DELETE /users/{id}.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',
]);
}
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.
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."]
}
}
Adding a New API:
php artisan make:api Product
Extending Functionality:
public function bulkDelete()).routes/api.php:
Route::delete('/users/bulk', [UserController::class, 'bulkDelete']);
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();
}
Authentication:
Protect generated APIs with Laravel’s auth middleware (e.g., auth:api):
Route::middleware('auth:api')->group(function () {
Route::apiResource('users', UserController::class);
});
Pagination: Enable pagination in the controller:
public function index()
{
return User::paginate(15);
}
API Versioning: Use Laravel’s route grouping for versioning:
Route::prefix('v1')->group(function () {
Route::apiResource('users', UserController::class);
});
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()
Route Conflicts:
/users vs. /admin/users).routes/api.php or use route prefixes:
Route::prefix('api/v1')->apiResource('users', UserController::class);
Validation Overrides:
rules():
public function rules()
{
return [
'email' => 'required|email|unique:users,email,'.$this->user->id,
];
}
Missing Middleware:
app/Http/Kernel.php or per-route:
Route::middleware(['cors', 'throttle:60'])->apiResource('users', UserController::class);
Database Relationships:
users/{user}/posts).apiResource with nested routes.Testing Challenges:
public function test_user_creation()
{
$this->actingAs($user)
->postJson('/api/users', ['name' => 'Test'])
->assertCreated();
}
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()
]);
}
Check Route Cache: Clear cached routes if changes aren’t reflecting:
php artisan route:clear
php artisan config:clear
Validate Requests Manually: If validation fails unexpectedly, test the request class directly:
$request = new StoreUserRequest();
$validator = \Validator::make($request->all(), $request->rules());
No Config File: If the package lacks a config file, hardcode settings in the service provider or environment variables.
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
}
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.
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.)
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
How can I help you explore Laravel packages today?