PHP code example of rakhavirgiandi / laravel-apigator

1. Go to this page and download the library: Download rakhavirgiandi/laravel-apigator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rakhavirgiandi / laravel-apigator example snippets


return [
    // Directory for generated controllers (relative to app/)
    'controller_directory' => 'Http/Controllers/API',

    // Directory for generated models (relative to app/)
    'model_directory' => 'Models',

    // Directory for generated services (relative to app/)
    'service_directory' => 'Services',

    // Route URL segment delimiter: '_' → /my_resource, '-' → /my-resource
    'route_delimiter' => '_',

    // Route file where generated routes are appended
    'route_file' => 'routes/api.php',

    // Default items per page for paginated responses
    'default_per_page' => 10,

    // Tables to skip when using --table=all
    'exclude_tables' => [
        'migrations',
        'password_resets',
        'password_reset_tokens',
        'failed_jobs',
        'personal_access_tokens',
        'sessions',
        'cache',
        'cache_locks',
        'jobs',
        'job_batches',
    ],
];

protected $fillable = [
    'name',
    'price',
    'category_id',
    'is_active',
    // ...
];

// Paginated list
ProductService::getList($request->all());

// Single record by ID
ProductService::getById($id, $request->all());

// Create (validates against createRules(), wraps in DB transaction)
ProductService::createRecord($request->all());

// Update (validates against updateRules(), wraps in DB transaction)
ProductService::updateRecord($id, $request->all());

// Delete (soft-delete aware)
ProductService::deleteRecord($id);

// DataTables server-side response
ProductService::getDatatable($request->all());

class ProductController extends Controller
{
    use ApiControllerTrait;

    public function index(Request $request): JsonResponse
    {
        $result = ProductService::getList($request->all());
        return $this->successResponse($result);
    }

    public function store(Request $request): JsonResponse
    {
        $record = ProductService::createRecord($request->all());
        return $this->successResponse($record, 'Product created successfully.', 201);
    }

    // show, update, destroy, datatable ...
}

// [APIGATOR_ENDPOINTS] products
Route::get('/products',              [ProductController::class, 'index']);
Route::get('/products/{id}',         [ProductController::class, 'show']);
Route::post('/products',             [ProductController::class, 'store']);
Route::patch('/products/{id}',       [ProductController::class, 'update']);
Route::delete('/products/{id}',      [ProductController::class, 'destroy']);
Route::post('/products_datatable',   [ProductController::class, 'datatable']);

public static function mapSchema(array $params = []): array
{
    $model = new self;

    return [
        'field' => [
            'id'          => ['column' => $model->table.'.id',          'alias' => 'id',          'type' => 'int'],
            'name'        => ['column' => $model->table.'.name',        'alias' => 'name',        'type' => 'string'],
            'price'       => ['column' => $model->table.'.price',       'alias' => 'price',       'type' => 'float'],
            'category_id' => ['column' => $model->table.'.category_id', 'alias' => 'category_id', 'type' => 'int'],
        ],
        'join'  => [],
        'where' => [],
    ];
}

'join' => [
    [
        'table' => 'categories as c',
        'type'  => 'left',
        'on'    => ['c.id', '=', $model->table.'.category_id'],
    ],
    [
        'table' => 'brands as b',
        'type'  => 'inner',
        'on'    => ['b.id', '=', $model->table.'.brand_id'],
    ],
],

'field' => [
    // ... own columns ...
    'category_name' => ['column' => 'c.name', 'alias' => 'category_name', 'type' => 'string'],
    'brand_name'    => ['column' => 'b.name', 'alias' => 'brand_name',    'type' => 'string'],
],

'where' => [
    // Only return published products
    ['column' => $model->table.'.is_published', 'operator' => '=',       'value' => 1],
    // Exclude archived records
    ['column' => $model->table.'.archived_at',  'operator' => 'IS NULL', 'value' => null],
],

'field' => [
    'full_name' => [
        'column' => "CONCAT(u.first_name, ' ', u.last_name)",
        'alias'  => 'full_name',
        'type'   => 'string',
        'is_raw' => true,
    ],
    'age' => [
        'column' => 'TIMESTAMPDIFF(YEAR, u.birth_date, CURDATE())',
        'alias'  => 'age',
        'type'   => 'int',
        'is_raw' => true,
    ],
],

public static function mapSchema(array $params = []): array
{
    $model = new self;

    $user_id = isset($params['user_id']) ? $params['user_id'] : null;

    $fields = [
        'id'   => ['column' => $model->table.'.id',   'alias' => 'id',   'type' => 'int'],
        'name' => ['column' => $model->table.'.name', 'alias' => 'name', 'type' => 'string'],
    ];

    // Only expose the cost_price field to admin users
    if ($user_id) {
        $fields['cost_price'] = ['column' => $model->table.'.cost_price', 'alias' => 'cost_price', 'type' => 'float'];
    }

    return [
        'field' => $fields,
        'join'  => [],
        'where' => [
            ['column' => $model->table.'.tenant_id', 'operator' => '=', 'value' => $user_id],
        ],
    ];
}

use Virgiandi\Apigator\Support\ApigatorException;

// 400 Bad Request
throw ApigatorException::withMessage('Invalid input.');

// 401 Unauthorized
throw ApigatorException::unauthorized();

// 403 Forbidden
throw ApigatorException::forbidden();

// 404 Not Found
throw ApigatorException::notFound(
    translationKey: 'errors.product_not_found',
    errorCode: 'PRODUCT_NOT_FOUND'
);

// 422 Unprocessable
throw ApigatorException::unprocessable();

// 500 Server Error
throw ApigatorException::serverError();

use Virgiandi\Apigator\Support\ApigatorValidationException;

// From a Laravel Validator instance
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
    throw ApigatorValidationException::fromValidator($validator);
}

// From a ValidationException
throw ApigatorValidationException::fromValidation($e);

// With manually specified errors
throw ApigatorValidationException::withErrors([
    'email' => ['This email is already registered.'],
    'items' => ['Cart cannot be empty.'],
]);

// Custom service method example
public static function getTopRated(array $params): array
{
    $query = Product::buildBaseQuery($params);
    $query->where('rating', '>=', 4.5)->orderBy('rating', 'desc');
    return $query->limit(10)->get()->toArray();
}

// 200 OK with data
$this->successResponse($data);

// 200 OK with custom message
$this->successResponse($data, 'Product updated successfully.');

// 201 Created
$this->successResponse($record, 'Product created.', 201);

// 400 Bad Request
$this->errorResponse('Something went wrong.', 400);

// 404 Not Found
$this->notFoundResponse('Product');

// 422 Validation Error
$this->validationErrorResponse($validationException);
bash
php artisan vendor:publish --tag=apigator-config
bash
php artisan apigator:generate --table=products

app/
├── Http/Controllers/API/ProductController.php
├── Models/Product.php
└── Services/ProductService.php

routes/api.php  ← 6 routes appended automatically

php artisan apigator:generate [options]
bash
php artisan apigator:generate --table=orders
bash
php artisan apigator:generate --table=all
bash
php artisan apigator:generate \
  --table=users \
  --model-dir=Domain/Users/Models \
  --service-dir=Domain/Users/Services \
  --controller-dir=Http/Controllers/V1
bash
php artisan apigator:generate --table=customers --connection=secondary_db
bash
php artisan apigator:generate --table=products --force