PHPackages                             rizkussef/laravel-crud-api - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. rizkussef/laravel-crud-api

ActiveLibrary[HTTP &amp; Networking](/categories/http)

rizkussef/laravel-crud-api
==========================

A clean, scalable Api CRUD package for the Service-based architecture for Laravel with advanced filtering, eager-loading relationships, and automatic resource resolution

v1.5.2(2mo ago)013MITPHPPHP ^8.1

Since Mar 9Pushed 2mo agoCompare

[ Source](https://github.com/RizkUssef/laravel-crud-api)[ Packagist](https://packagist.org/packages/rizkussef/laravel-crud-api)[ Docs](https://github.com/rizkussef/laravel-crud-api)[ RSS](/packages/rizkussef-laravel-crud-api/feed)WikiDiscussions master Synced 3w ago

READMEChangelogDependencies (9)Versions (6)Used By (0)

🚀 Laravel CRUD Api Package
==========================

[](#-laravel-crud-api-package)

[![Latest Version on Packagist](https://camo.githubusercontent.com/0ffc9476f23efb9d1bf8d6b973441f02f3675cd37454a61e07eed544e051271f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f72697a6b75737365662f6c61726176656c2d637275642d6170692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/rizkussef/laravel-crud-api)[![Total Downloads](https://camo.githubusercontent.com/d47ba1990ca96e6150177f5cba1689045c5c28ac4d8fa6e2ae806b50a3057cd7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f72697a6b75737365662f6c61726176656c2d637275642d6170692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/rizkussef/laravel-crud-api)[![License](https://camo.githubusercontent.com/66dd7e93f2f0a9eb6d39a06df45c74c0397c7435a478281c3c6006fddfb05354/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f72697a6b75737365662f6c61726176656c2d637275642d6170692e7376673f7374796c653d666c61742d737175617265)](LICENSE)

A clean, scalable **Api CRUD architecture for Laravel**, built around a reusable **Base Service** and **Base Controller** with automatic:

- ✅ Model Resolution
- ✅ Resource Resolution
- ✅ Collection Handling
- ✅ Pagination
- ✅ Advanced Filtering (=, !=, &gt;, &lt;, &gt;=, &lt;=, LIKE, IN, BETWEEN, NULL checks, Date operations)
- ✅ Eager Loading Relationships
- ✅ API Response Formatting
- ✅ Auto-Validation using Form Requests
- ✅ Auto Creation of Model, Resource, Requests, Controller, Service, Migration using Command

Designed to eliminate repetitive CRUD logic while keeping your application clean and maintainable. Pass filters and relationships directly from your frontend to dynamically build optimized queries with full control over data retrieval.

---

📦 Installation
==============

[](#-installation)

Install via Composer:

```
composer require rizkussef/laravel-crud-api
```

If needed, manually register the provider in:

```
config/app.php
```

```
Rizkussef\LaravelCrudApi\ApiCrudServiceProvider::class,
```

---

⚙️ Publish Configuration
========================

[](#️-publish-configuration)

```
php artisan vendor:publish --provider="Rizkussef\LaravelCrudApi\ApiCrudServiceProvider" --tag=config
```

This will publish:

```
config/api-crud.php
```

Example:

```
return [
    'paginate' => 15,
];
```

---

🏗 Architecture
==============

[](#-architecture)

```
App
 ├── Models
 │     └── User.php
 ├── Services
 │     └── UserService.php
 ├── Http
 │     ├── Controllers
 │     │      └── UserController.php
 │     ├── Requests
 │     │      ├── UserRequest.php
 │     │      └── UserUpdateRequest.php
 │     └── Resources
 │            └── UserResource.php

```

---

⚡ Artisan Generator Command
===========================

[](#-artisan-generator-command)

The absolute fastest way to get started is by using the built-in Artisan generator. This powerful command scaffolds a fully functional CRUD API endpoint in seconds!

```
php artisan api-crud:make {Model}
```

### 🎯 Example: Creating an Article API

[](#-example-creating-an-article-api)

```
php artisan api-crud:make Article
```

**What happens behind the scenes?** The command automatically generates all layers required for an API CRUD operation:

LayerGenerated FileDescription**Model**`App\Models\Article.php`The Eloquent model (along with its database migration).**Resource**`App\Http\Resources\ArticleResource.php`Automatically serializes and formats your JSON response.**Requests**`App\Http\Requests\ArticleRequest.php`
`ArticleUpdateRequest.php`Dedicated Form validation classes (Auto-validated by Controller).**Service**`App\Services\ArticleService.php`Core business logic layer (Extends `ApiCrudService`).**Controller**`App\Http\Controllers\ArticleController.php`Handles routing and formatting (Extends `ApiCrudController`).### ⚙️ Available Options

[](#️-available-options)

OptionDescriptionExample`--no-migration`Tells the generator to skip database migration file creation.`php artisan api-crud:make User --no-migration`Once generated, just register your new endpoint in `routes/api.php` and you're fully operational!

```
Route::apiResource('articles', ArticleController::class);
```

---

🛠 Manual Setup (Step-by-Step)
=============================

[](#-manual-setup-step-by-step)

### 1️⃣ Create a Service

[](#1️⃣-create-a-service)

```
namespace App\Services;

use Rizkussef\LaravelCrudApi\Services\ApiCrudService;

class UserService extends ApiCrudService
{
    // Add custom business logic here if needed
}
```

### 🔎 Automatic Resolution (Models, Resources, and Form Requests)

[](#-automatic-resolution-models-resources-and-form-requests)

The architecture heavily relies on naming conventions to automatically resolve dependencies:

```
UserService → App\Models\User
UserService → App\Http\Resources\UserResource
UserController → App\Http\Requests\UserRequest (Used for store)
UserController → App\Http\Requests\UserUpdateRequest (Used for update)

```

No need to manually inject or define the Model, Resource, or Form Requests. `ApiCrudController` automatically validates inbound requests using the resolved Form Request before passing data to the Service.

---

2️⃣ Create a Controller
-----------------------

[](#2️⃣-create-a-controller)

```
namespace App\Http\Controllers;

use App\Services\UserService;
use Rizkussef\LaravelCrudApi\Http\Controllers\ApiCrudController;

class UserController extends ApiCrudController {
    public function __construct(UserService $service)
    {
        parent::__construct($service);
    }
}
```

Just Inject the specific service for this controller.

---

� Filters &amp; Relationships
=============================

[](#-filters--relationships)

The package includes powerful filtering and eager-loading capabilities. Pass filters and relationships from the frontend to dynamically build queries. They can be passed either as array parameters or as JSON-encoded strings.

Available Filter Operators
--------------------------

[](#available-filter-operators)

### Comparison Operators

[](#comparison-operators)

```
// Equal / Greater Than / Less Than
['age' => ['operator' => '=', 'value' => 25]]
['age' => ['operator' => '>', 'value' => 18]]
['age' => ['operator' => '>=', 'value' => 18]]
['age' => ['operator' => '', value: 18 }
      },
      relationships: ['profile', 'comments'],
      per_page: 15
    }
  });

  console.log(data);
};
```

Backend Services Examples
-------------------------

[](#backend-services-examples)

### Another Service Calling This Service

[](#another-service-calling-this-service)

```
namespace App\Services;

use App\Services\UserService;

class ReportService
{
    public function __construct(private UserService $userService) {}

    /**
     * Generate active users report
     */
    public function getActiveUsersReport()
    {
        $filters = [
            'status' => 'active',
            'created_at' => [
                'operator' => 'date',
                'value' => now()->subMonth()->format('Y-m-d')
            ]
        ];

        $relationships = ['profile', 'department'];

        return $this->userService->index($filters, $relationships);
    }

    /**
     * Get premium users with pagination
     */
    public function getPremiumUsers($page = 1)
    {
        $filters = [
            'subscription_type' => 'premium',
            'last_payment_date' => [
                'operator' => '!=null'
            ]
        ];

        $relationships = ['subscription', 'profile'];

        return $this->userService->getPaginated(
            perPage: 50,
            filters: $filters,
            relationships: $relationships
        );
    }

    /**
     * Search users by multiple criteria
     */
    public function searchUsers($name, $department, $minAge)
    {
        $filters = [
            'name' => $name,
            'department_id' => $department,
            'age' => [
                'operator' => '>=',
                'value' => $minAge
            ]
        ];

        return $this->userService->index($filters, ['profile', 'department']);
    }
}
```

---

�🔁 Built-in CRUD Methods
========================

[](#-built-in-crud-methods)

The BaseCrudController provides:

- `index()` – List records
- `getPaginated($perPage)` - Paginate list of records
- `show($id)` – Show single record
- `store(Request $request)` – Automatically resolves and validates the incoming Request using the associated Form Request, then creates record
- `update(Request $request, $id)` – Automatically resolves and validates using the associated Update Form Request, then updates record
- `destroy($id)` – Delete record

Controller handles validation &amp; response formatting. All business logic is handled inside **ApiCrudService**.

---

📄 Automatic Resource Handling
=============================

[](#-automatic-resource-handling)

### Single Item

[](#single-item)

```
return new UserResource($user);
```

### Collection

[](#collection)

```
return UserResource::collection($users);
```

Automatically handled by the base service.

### No Resource

[](#no-resource)

```
// No UserResource exists
return $user; // returns full user model data
```

If the corresponding Resource class does not exist, the base controller will return the raw model data instead of a resource.

---

📊 Example JSON Response
=======================

[](#-example-json-response)

### GET /users

[](#get-users)

```
{
  "data": [
    {
      "id": 1,
      "name": "John Doe"
    }
  ],
  "meta": {
    "current_page": 1,
    "per_page": 15
  }
}
```

---

🧠 Best Practices
================

[](#-best-practices)

✔ Use the Artisan Generator Command to create all layers automatically.
✔ Keep business logic inside Model-specific services.
✔ Keep controllers thin.
✔ Extend ApiCrudService instead of modifying it.
✔ Use Resources for API formatting.
✔ Use filters and relationships to avoid N+1 query problems.

### Example 1: Simple Business Logic with Filters

[](#example-1-simple-business-logic-with-filters)

```
namespace App\Services;

use Rizkussef\LaravelCrudApi\Services\ApiCrudService;

class UserService extends ApiCrudService
{
    /**
     * Activate user
     */
    public function activate($id)
    {
        $user = $this->model->findOrFail($id);
        $user->update(['active' => true]);
        return $this->applyResource($user);
    }

    /**
     * Get active users in a department
     */
    public function getActiveDepartmentUsers($departmentId, $perPage = 15)
    {
        $filters = [
            'active' => true,
            'department_id' => $departmentId
        ];

        $relationships = ['department', 'profile'];

        return $this->getPaginated($perPage, $filters, $relationships);
    }
}
```

### Example 2: Complex Filtering with Date Range

[](#example-2-complex-filtering-with-date-range)

```
namespace App\Services;

use Rizkussef\LaravelCrudApi\Services\ApiCrudService;

class OrderService extends ApiCrudService
{
    /**
     * Get high-value orders in date range with customer details
     */
    public function getHighValueOrders($minAmount, $startDate, $endDate, $perPage = 20)
    {
        $filters = [
            'total_amount' => [
                'operator' => '>=',
                'value' => $minAmount
            ],
            'created_at' => [
                'operator' => 'between',
                'value' => [$startDate, $endDate]
            ],
            'status' => [
                'operator' => 'in',
                'value' => ['completed', 'shipped']
            ]
        ];

        $relationships = ['customer', 'items.product', 'payment'];

        return $this->getPaginated($perPage, $filters, $relationships);
    }

    /**
     * Search orders by customer name and status
     */
    public function searchOrders($customerName, $statuses)
    {
        $filters = [
            'customer_name' => [
                'operator' => 'like',
                'value' => $customerName
            ],
            'status' => [
                'operator' => 'in',
                'value' => $statuses
            ]
        ];

        return $this->index($filters, ['customer', 'items']);
    }
}
```

### Example 3: Filtering with NULL Checks

[](#example-3-filtering-with-null-checks)

```
namespace App\Services;

use Rizkussef\LaravelCrudApi\Services\ApiCrudService;

class ArticleService extends ApiCrudService
{
    /**
     * Get published articles with authors and comments
     */
    public function getPublishedArticles($perPage = 15)
    {
        $filters = [
            'status' => 'published',
            'published_at' => [
                'operator' => '!null'  // IS NOT NULL
            ]
        ];

        $relationships = ['author', 'comments.author', 'tags'];

        return $this->getPaginated($perPage, $filters, $relationships);
    }

    /**
     * Get articles pending review (no reviewer assigned)
     */
    public function getPendingReview()
    {
        $filters = [
            'status' => 'draft',
            'reviewer_id' => [
                'operator' => 'null'  // IS NULL
            ]
        ];

        return $this->index($filters, ['author']);
    }
}
```

🔌 Dependency Injection
======================

[](#-dependency-injection)

ApiCrudService is bound in the container via the Service Provider, so it can be injected anywhere.

---

🔧 Extending
===========

[](#-extending)

You can extend:

- ApiCrudController
- ApiCrudService
- Pagination configuration

And you can use:

- API Response Trait
- Filter Query Trait
- Relationship Query Trait

---

🛣 Example Routes
================

[](#-example-routes)

```
Route::apiResource('users', UserController::class);
```

---

👨‍💻 Author &amp; Support
========================

[](#‍-author--support)

**Developed by Rizk Ussef**

A fullstack developer passionate about creating clean, maintainable architecture patterns and reusable solutions for building scalable applications across frontend and backend ecosystems.

### Get in Touch

[](#get-in-touch)

- **GitHub:** [@rizkussef](https://github.com/rizkussef)
- **Email:**
- **Issues &amp; Feedback:** [GitHub Issues](https://github.com/rizkussef/laravel-crud-api/issues)

---

🤝 Contributing
==============

[](#-contributing)

Contributions are welcome! If you find bugs or have feature suggestions, please open an issue or submit a pull request.

---

📄 License
=========

[](#-license)

MIT License - see [LICENSE](LICENSE) file for details.

###  Health Score

38

—

LowBetter than 83% of packages

Maintenance86

Actively maintained with recent releases

Popularity5

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% 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 ~9 days

Total

5

Last Release

73d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/3f71fc860d07c78f9ceb026be3ea529c3cc27957b6e2631f778c68a2d01761ed?d=identicon)[RizkUssef](/maintainers/RizkUssef)

---

Top Contributors

[![RizkUssef](https://avatars.githubusercontent.com/u/139924623?v=4)](https://github.com/RizkUssef "RizkUssef (12 commits)")

---

Tags

apilaravelrestpaginationlaravel-packagecrudquery builderfilteringlaravel crud generatorRelationshipsbase-controllereager-loadingapi-resourceslaravel crud operationsservice-based-architecturebase-servicelaravel api core crudlaravel base crud apilaravel-crud-packagelaravel crud api

###  Code Quality

TestsPHPUnit

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/rizkussef-laravel-crud-api/health.svg)

```
[![Health](https://phpackages.com/badges/rizkussef-laravel-crud-api/health.svg)](https://phpackages.com/packages/rizkussef-laravel-crud-api)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k51.0M7.6k](/packages/larastan-larastan)[api-platform/laravel

API Platform support for Laravel

59156.3k11](/packages/api-platform-laravel)[calebdw/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

15104.9k4](/packages/calebdw-larastan)

PHPackages © 2026

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