PHPackages                             mehedi8gb/api-crudify - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. mehedi8gb/api-crudify

ActiveLibrary[API Development](/categories/api)

mehedi8gb/api-crudify
=====================

Automate CRUD operations for Laravel APIs.

4.2.2(1mo ago)1452MITPHPPHP ^8.2CI failing

Since Sep 7Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/mehedi8gb/api-crudify)[ Packagist](https://packagist.org/packages/mehedi8gb/api-crudify)[ Docs](https://github.com/mehedi8gb/api-crudify)[ RSS](/packages/mehedi8gb-api-crudify/feed)WikiDiscussions main Synced today

READMEChangelog (10)Dependencies (13)Versions (38)Used By (0)

Api Crudify
===========

[](#api-crudify)

Laravel API Engine for Scalable Query-Driven Applications
---------------------------------------------------------

[](#laravel-api-engine-for-scalable-query-driven-applications)

[![Latest Version on Packagist](https://camo.githubusercontent.com/3e836c63066427b4dbd7e08bf0ae64c5b981f60f6909567ac77f64074c34a76b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d65686564693867622f6170692d637275646966792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mehedi8gb/api-crudify)[![Total Downloads](https://camo.githubusercontent.com/26953a73ebee39bfaf0de770ab203056079599ad13fdf2a00c763e1561a95576/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d65686564693867622f6170692d637275646966792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mehedi8gb/api-crudify)[![License](https://camo.githubusercontent.com/cfd888f86b936e51736d3bbca065629a51f467bb02d42f7f9258399436e6fdf9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d65686564693867622f6170692d637275646966792e7376673f7374796c653d666c61742d737175617265)](https://github.com/mehedi8gb/api-crudify/blob/main/LICENSE.md)

**Api Crudify** is a professional-grade Laravel package that automates generation of robust, scalable, and standardized API CRUD components. It enforces the **Service-Repository** design pattern and implements a **Chain of Responsibility** pipeline for complex API queries — filtering, sorting, relation loading, soft deletes, and pagination — all driven by query parameters.

---

🚀 Key Features
--------------

[](#-key-features)

- **Standardized Architecture** — Generates Controller, Service, Repository, Model, FormRequests, Resource, Migration, Factory, Seeder, and Feature Test in one command.
- **Chain of Responsibility Query Pipeline** — Modular, ordered handlers process every API request: SoftDelete → Relations → Filter → Sort → Pagination.
- **Advanced Dynamic Filtering** — Frontend-friendly `?q=` shorthand plus low-level `?where=` and `?orWhere=` with relation traversal support.
- **Smart Relation Loading** — Respects explicitly passed relations, model `$with`, or Eloquent eager loads automatically.
- **Soft Delete Awareness** — `?trashed=with` or `?trashed=only` query params built in.
- **Domain-Driven Design Ready** — Full support for nested namespaces: `V1/Inventory/Product`.
- **Auto-Restoration** — Detects and restores any missing base classes on every `crudify:make` run.
- **Route Management** — Automatically registers API routes and `use` statements.
- **Helper Utilities** — Global helper functions for responses, caching, payload filtering, and more.

---

📦 Installation
--------------

[](#-installation)

```
composer require mehedi8gb/api-crudify --dev
```

Run the installer to bootstrap all base classes and configure autoloading:

```
php artisan crudify:install
```

This command will:

- Copy all base classes, interfaces, and query handlers into your `app/` directory
- Add `app/Helpers/Helpers.php` to `composer.json` autoload files
- Run `composer dump-autoload` automatically

---

🛠 Usage
-------

[](#-usage)

```
php artisan crudify:make {Name}
```

### Examples

[](#examples)

```
# Simple CRUD
php artisan crudify:make Product

# Versioned / domain-specific
php artisan crudify:make V1/Inventory/Category

# With Postman schema export
php artisan crudify:make Product --export-api-schema
```

---

📂 Generated Components
----------------------

[](#-generated-components)

ComponentPath**Controller**`app/Http/Controllers/{Path}/{Name}Controller.php`**Model**`app/Models/{Path}/{Name}.php`**Service**`app/Services/{Path}/{Name}Service.php`**Repository**`app/Repositories/{Path}/{Name}Repository.php`**Form Requests**`app/Http/Requests/{Path}/{Name}StoreRequest.php` &amp; `UpdateRequest.php`**Resource**`app/Http/Resources/{Path}/{Name}Resource.php`**Migration**`database/migrations/YYYY_MM_DD_create_{names}_table.php`**Factory**`database/factories/{Path}/{Name}Factory.php`**Seeder**`database/seeders/{Path}/{Name}Seeder.php`**Feature Test**`tests/Feature/{Path}/{Name}Test.php`---

🏗 Architecture Overview
-----------------------

[](#-architecture-overview)

Every generated CRUD follows a strict 3-layer architecture:

```
HTTP Request
     │
     ▼
┌─────────────────────────────────┐
│         Controller              │  ← HTTP only: validate, call service, return response
│   (extends Controller)          │
└──────────────┬──────────────────┘
               │
               ▼
┌─────────────────────────────────┐
│           Service               │  ← Business logic, orchestration
│   (extends BaseService)         │
└──────────────┬──────────────────┘
               │
               ▼
┌─────────────────────────────────┐
│          Repository             │  ← Data access only, Eloquent queries
│   (extends BaseRepository)      │
└──────────────┬──────────────────┘
               │
               ▼
┌─────────────────────────────────┐
│     Query Pipeline              │  ← Chain of Responsibility
│  SoftDelete → Relations →       │
│  Filter → Sort → Pagination     │
└─────────────────────────────────┘

```

### Real-World Example

[](#real-world-example)

**Controller** — HTTP only, no business logic:

```
final class ProductController extends Controller
{
    public function __construct(
        private readonly ProductService $service
    ) {}

    public function index(): JsonResponse
    {
        $collection = $this->service->getProductsCollection();
        return $this->successResponse('Products retrieved successfully', $collection);
    }
}
```

**Service** — orchestrates business logic:

```
class ProductService extends BaseService
{
    public function __construct(
        protected ProductRepository $productRepository,
        protected Request $request
    ) {
        parent::__construct($productRepository, $request);
    }

    public function getProductsCollection(): array
    {
        $data = $this->productRepository->getProductsData();
        return $this->prepareResourceResponse($data, ProductResource::class);
    }
}
```

**Repository** — data access only:

```
class ProductRepository extends BaseRepository
{
    public function __construct(Product $model, protected Request $request)
    {
        parent::__construct($model, $request);
    }

    public function getProductsData(array $with = ['category', 'tags']): array
    {
        return $this->handleApiQueryRequest($this->query(), $with);
    }
}
```

---

⚡ Query Pipeline — Chain of Responsibility
------------------------------------------

[](#-query-pipeline--chain-of-responsibility)

Every API request through `handleApiQueryRequest()` passes through this ordered pipeline:

```
Builder + Request
       │
       ▼
┌──────────────────┐
│ SoftDeleteHandler│  ?trashed=with|only|default
└────────┬─────────┘
         ▼
┌──────────────────┐
│  RelationHandler │  Explicit $with → model $with → Eloquent eager loads
└────────┬─────────┘
         ▼
┌──────────────────┐
│  FilterHandler   │  ?q= / ?where= / ?orWhere= / ?exclude= / ?operator=
└────────┬─────────┘
         ▼
┌──────────────────┐
│   SortHandler    │  ?sortBy= / ?sortOrder=asc|desc
└────────┬─────────┘
         ▼
┌──────────────────┐
│PaginationHandler │  ?page= / ?limit= / ?limit=all
└────────┬─────────┘
         ▼
  { meta, data }

```

---

🔍 Query Parameter Reference
---------------------------

[](#-query-parameter-reference)

### Filtering

[](#filtering)

ParameterDescriptionExample`?q=`Frontend-friendly shorthand filter`?q=title=phone``?where=`Direct column filter`?where=status,active``?orWhere=`OR column filter`?orWhere=type,admin``?operator=`Comparison operator`?operator==` or `?operator=like``?exclude=`Exclude a specific value`?exclude=status,deleted`**Relation filtering via `?where=`:**

```
?where=with:category,name,Electronics
?where=with:category.parent,name,Tech

```

**Frontend shorthand `?q=` with pipe-separated conditions:**

```
?q=title=phone|status=active
?q=category.name=Electronics

```

**Complex nested relational query conditions:**

```
?q=posts.category.child.status=active
?q=posts.createdBy.userId=10

```

**`?or=true` converts multiple `?q=` conditions to `orWhere`:**

```
?q=title=phone|brand=apple&or=true

```

---

### Sorting

[](#sorting)

ParameterDefaultExample`?sortBy=``created_at``?sortBy=price``?sortOrder=``desc``?sortOrder=asc`> Safe against SQL injection — column existence is verified against the schema before applying. Skipped if the builder already has an `orderBy` applied.

---

### Soft Deletes

[](#soft-deletes)

ParameterBehaviour`?trashed=with`Include soft-deleted records`?trashed=only`Return only soft-deleted records*(omitted)*Exclude soft-deleted records (default)---

### Pagination

[](#pagination)

ParameterDefaultDescription`?page=``1`Current page`?limit=``10`Records per page`?limit=all`—Returns all records, no pagination**Response structure:**

```
{
  "meta": {
    "page": 1,
    "limit": 10,
    "total": 245,
    "totalPage": 25
  },
  "data": [ ... ]
}
```

---

### Relation Loading

[](#relation-loading)

Relations are resolved in this priority order:

1. Explicit `$with` array passed to `handleApiQueryRequest()`
2. Model-level `$with` property
3. Eloquent registered eager loads via `getEagerLoads()`

---

🧰 Helper Functions
------------------

[](#-helper-functions)

Global utility functions available after install:

FunctionDescription`sendSuccessResponse($message, $data, $status)`Standardized JSON success response`sendErrorResponse($exception, $status)`Standardized JSON error response with environment-aware detail`validationException($payload, $key)`Throw a `ValidationException` from array or string`filterPayload($data, $allowedKeys)`Keep only allowed keys from an array`cacheQuery($query, $method, $args, $ttl)`Execute and cache a query with tag-based invalidation`generateCacheKey($builder, $request, $tenantId)`Generate deterministic cache key from query state`getCreatedAtColumn($builder|$model)`Resolve model's `CREATED_AT` column safely`getResourceClass($model)`Auto-resolve `{Model}Resource` class or fallback to `DefaultResource``deepMerge($original, $new)`Deep array merge with force-replace support`processNestedArray($existing, $payload)`Merge and deduplicate nested arrays by `id``convertStatus($status)`Convert boolean to `1`/`0``generateUniqueNumber($prefix)`Generate a unique prefixed identifier`getFormatedDate($carbon)`Human-readable date with diff: `"2 days ago (14th April at 08:21 AM in 2025)"`---

⚙️ Base Classes Installed
-------------------------

[](#️-base-classes-installed)

After `crudify:install`, the following are placed in your `app/` directory:

```
app/
├── IContracts/
│   ├── Repositories/  (IRepository, IReadRepository, IWriteRepository)
│   └── Services/      (IService, IReadService, IWriteService)
├── Repositories/V1/BaseRepository.php
├── Services/V1/BaseService.php
├── Models/Model.php
├── Helpers/Helpers.php
├── Core/
│   ├── Query/
│   │   ├── HandleApiQueryRequest.php
│   │   ├── Contracts/IQueryHandler.php
│   │   └── Handlers/
│   │       ├── AbstractQueryHandler.php
│   │       ├── Core/
│   │       │   ├── FilterHandler.php
│   │       │   ├── PaginationHandler.php
│   │       │   ├── RelationHandler.php
│   │       │   ├── SoftDeleteHandler.php
│   │       │   └── SortHandler.php
│   │       └── Optimization/CacheHandler.php
│   └── ClientQuery/   (mirror of Query for client-facing APIs)
└── Http/Resources/DefaultResource.php

```

---

📜 Changelog
-----------

[](#-changelog)

Please see [CHANGELOG](CHANGELOG.md) for recent changes.

✨ Credits
---------

[](#-credits)

- [MD Mehedi Hasan](https://github.com/mehedi8gb)

📜 License
---------

[](#-license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

49

—

FairBetter than 94% of packages

Maintenance89

Actively maintained with recent releases

Popularity16

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 97.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~39 days

Recently: every ~47 days

Total

26

Last Release

57d ago

Major Versions

v1.1.91 → v2.0.02024-05-14

v1.1.9 → v2.0.12024-05-14

2.0.3 → v3.0.22025-03-20

v3.0.2 → v4.0.12025-10-30

PHP version history (2 changes)1.0.0PHP ^8.1

v2.0.1PHP ^8.2

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/67598625?v=4)[MD Mehedi Hasan](/maintainers/mehedi8gb)[@mehedi8gb](https://github.com/mehedi8gb)

---

Top Contributors

[![mehedi8gb](https://avatars.githubusercontent.com/u/67598625?v=4)](https://github.com/mehedi8gb "mehedi8gb (81 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

api-crudapi-enginecrudquery-drivenapilaravellaravel-packagecrudrestfullaravel crud generatorLaravel Development Toolslaravel package developmentlaravel api crudlaravel restful apilaravel api automationlaravel api developmentlaravel php frameworklaravel web services

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/mehedi8gb-api-crudify/health.svg)

```
[![Health](https://phpackages.com/badges/mehedi8gb-api-crudify/health.svg)](https://phpackages.com/packages/mehedi8gb-api-crudify)
```

###  Alternatives

[darkaonline/l5-swagger

OpenApi or Swagger integration to Laravel

3.0k37.6M134](/packages/darkaonline-l5-swagger)[knuckleswtf/scribe

Generate API documentation for humans from your Laravel codebase.✍

2.3k14.2M63](/packages/knuckleswtf-scribe)[binaryk/laravel-restify

Laravel REST API helpers

677415.0k](/packages/binaryk-laravel-restify)[kyon147/laravel-shopify

Shopify package for Laravel to aide in app development

485302.1k](/packages/kyon147-laravel-shopify)[rupadana/filament-api-service

A simple api service for supporting filamentphp

210120.6k7](/packages/rupadana-filament-api-service)[api-platform/laravel

API Platform support for Laravel

58171.5k14](/packages/api-platform-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
