PHPackages                             mahmoud-almalah/laravel-api-helpers - 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. mahmoud-almalah/laravel-api-helpers

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

mahmoud-almalah/laravel-api-helpers
===================================

Standardized API responses for Laravel applications.

v2.0.1(2mo ago)1666MITPHPPHP ^8.3CI passing

Since Apr 14Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/mahmoud-almalah/laravel-api-helpers)[ Packagist](https://packagist.org/packages/mahmoud-almalah/laravel-api-helpers)[ Docs](https://github.com/mahmoud-almalah/laravel-api-helpers)[ GitHub Sponsors](https://github.com/mahmoud-almalah)[ RSS](/packages/mahmoud-almalah-laravel-api-helpers/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (9)Versions (11)Used By (0)

Laravel API Helpers
===================

[](#laravel-api-helpers)

[![Tests](https://github.com/mahmoud-almalah/laravel-api-helpers/actions/workflows/test.yml/badge.svg)](https://github.com/mahmoud-almalah/laravel-api-helpers/actions)[![Packagist](https://camo.githubusercontent.com/602b5246c0a4bf1d61cda76b7bf0ac46878607da1a1a772d46f226e01a53bb1f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d61686d6f75642d616c6d616c61682f6c61726176656c2d6170692d68656c70657273)](https://packagist.org/packages/mahmoud-almalah/laravel-api-helpers)[![License: MIT](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)

A clean and elegant Laravel package that provides a consistent and customizable structure for your API development. It includes standardized responses, strict Data Transfer Objects (DTOs), API query filtering, and exception handling.

---

✨ Features
----------

[](#-features)

- ✅ **Consistent JSON Responses** for success, errors, collections, and resources.
- ✅ **Data Transfer Objects (DTO)** for type-safe request handling and validation.
- ✅ **API Query Filtering** to easily filter and sort Eloquent models.
- ✅ **Standardized Exception Handling** via `ApiExceptionHandler` class.
- ✅ **Laravel 11+** Support.
- ✅ Full test coverage with [Pest](https://pestphp.com).

---

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

[](#-installation)

```
composer require mahmoud-almalah/laravel-api-helpers
```

---

⚙️ Configuration
----------------

[](#️-configuration)

You can publish the configuration file to customize the internal settings:

```
php artisan vendor:publish --tag=api-helpers-config
```

This will publish `config/api-helpers.php`.

---

🚀 Usage
-------

[](#-usage)

### 1️⃣ Standardized Responses

[](#1️⃣-standardized-responses)

Use the `ApiResponse` class to return consistent JSON responses.

#### Success Response

[](#success-response)

```
use MahmoudAlmalah\LaravelApiHelpers\Responses\ApiResponse;

public function index()
{
    return ApiResponse::success(
        data: ['foo' => 'bar'],
        message: 'Operation successful'
    );
}
```

#### Error Response

[](#error-response)

```
use MahmoudAlmalah\LaravelApiHelpers\Responses\ApiResponse;
use Symfony\Component\HttpFoundation\Response;

public function error()
{
    return ApiResponse::error(
        message: 'Something went wrong',
        status: Response::HTTP_BAD_REQUEST
    );
}
```

#### Resource/Model Response

[](#resourcemodel-response)

Wraps your Eloquent model or JsonResource.

```
use MahmoudAlmalah\LaravelApiHelpers\Responses\ApiResponse;
use App\Http\Resources\UserResource;

public function show(User $user)
{
    return ApiResponse::model(
        key: 'user',
        resource: new UserResource($user),
        message: 'User retrieved successfully'
    );
}
```

#### Collection Response

[](#collection-response)

Handles pagination metadata automatically.

```
use MahmoudAlmalah\LaravelApiHelpers\Responses\ApiResponse;
use App\Http\Resources\UserResource;

public function index()
{
    $users = User::paginate(10);

    return ApiResponse::collection(
        key: 'users',
        resource: UserResource::collection($users),
        message: 'Users list'
    );
}
```

---

### 2️⃣ Data Transfer Objects (DTO)

[](#2️⃣-data-transfer-objects-dto)

Replace basic arrays or `FormRequest` validation with strict DTOs.

**Define your DTO:**

```
namespace App\DTOs;

use MahmoudAlmalah\LaravelApiHelpers\DTO\DataTransferObject;

class CreateUserDTO extends DataTransferObject
{
    public string $name;
    public string $email;
    public ?string $role = 'user';

    /**
     * Define validation rules.
     */
    public static function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'unique:users,email'],
            'role' => ['nullable', 'string', 'in:admin,user'],
        ];
    }
}
```

**Use in Controller:**

```
public function store(Request $request)
{
    // Validates request and maps to DTO
    $dto = CreateUserDTO::fromRequest($request);

    // Use strictly typed properties
    User::create($dto->toArray());

    return ApiResponse::success(message: 'User created');
}
```

---

### 3️⃣ API Query Filtering &amp; Sorting

[](#3️⃣-api-query-filtering--sorting)

Allow clients to filter and sort results easily via query parameters.

**In your Model:**

```
use MahmoudAlmalah\LaravelApiHelpers\Concerns\HasApiFilters;

class User extends Model
{
    use HasApiFilters;

    // Allow filtering by these columns
    protected array $filterable = ['status', 'role', 'type'];

    // Allow sorting by these columns
    protected array $sortable = ['created_at', 'name'];

    // Define custom filter logic (optional)
    public function scopeActive(Builder $query, $value): void
    {
        if ($value) {
            $query->where('active', true);
        }
    }
}
```

**In Controller:**

```
// GET /users?filter[status]=active&filter[active]=1&sort=-created_at
public function index(Request $request)
{
    $users = User::filter($request->query('filter'))
                 ->sort($request->query('sort'))
                 ->paginate();

    return ApiResponse::collection('users', UserResource::collection($users));
}
```

---

### 4️⃣ Standardized Exception Handling

[](#4️⃣-standardized-exception-handling)

Catch exceptions and return consistent JSON error responses, including detailed debug info in local development.

**Setup in `bootstrap/app.php` (Laravel 11+):**

```
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Http\Request;
use MahmoudAlmalah\LaravelApiHelpers\Exceptions\ApiExceptionHandler;

return Application::configure(basePath: dirname(__DIR__))
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->render(function (Throwable $e, Request $request) {
            if ($request->is('api/*')) {
                return ApiExceptionHandler::render($e);
            }
        });
    })->create();
```

**Debug Info (Local Environment):**When `APP_ENV=local`, exceptions will include debug details:

```
{
    "success": false,
    "message": "Call to undefined method App\\Models\\User::unknown()",
    "status": 500,
    "debug": {
        "exception": {
            "class": "BadMethodCallException",
            "file": "/var/www/html/app/Http/Controllers/UserController.php",
            "line": 45,
            "trace": [...]
        },
        "request": {
            "method": "GET",
            "url": "http://localhost/api/users",
            "input": []
        },
        "time": "2023-10-25T14:30:00+00:00"
    }
}
```

In **Production**, it safely returns:

```
{
    "success": false,
    "message": "Server Error",
    "status": 500
}
```

---

✅ Output Format
---------------

[](#-output-format)

Success Response:

```
{
  "success": true,
  "message": "Users list",
  "data": {
    "users": [...]
  },
  "meta": {
    "current_page": 1,
    "total": 50
  }
}
```

Error Response:

```
{
  "success": false,
  "message": "Resource not found",
  "status": 404
}
```

---

🧪 Testing
---------

[](#-testing)

Run the test suite:

```
composer test
```

📄 License
---------

[](#-license)

The MIT License (MIT). See [LICENSE](LICENSE) for more information.

###  Health Score

45

—

FairBetter than 92% of packages

Maintenance83

Actively maintained with recent releases

Popularity18

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity58

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 ~34 days

Recently: every ~77 days

Total

10

Last Release

86d ago

Major Versions

v1.2.0 → v2.0.02026-02-09

### Community

Maintainers

![](https://www.gravatar.com/avatar/52a4860563ee6a9552196f87b53d9a4d38453a7c5a2e7ecd3910a02f47428bd2?d=identicon)[mahmoud-almalah](/maintainers/mahmoud-almalah)

---

Top Contributors

[![mahmoud-almalah](https://avatars.githubusercontent.com/u/75377167?v=4)](https://github.com/mahmoud-almalah "mahmoud-almalah (25 commits)")

---

Tags

apilaravellaravel-packageresponsableshttpresponsejsonapilaravelvalidationhelpersform-requestlaravel-api

###  Code Quality

TestsPest

Static AnalysisPHPStan, Rector

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/mahmoud-almalah-laravel-api-helpers/health.svg)

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

###  Alternatives

[vinelab/http

An http library developed for the laravel framework. aliases itself as HttpClient

59300.2k11](/packages/vinelab-http)[guanguans/laravel-api-response

Normalize and standardize Laravel API response data structure. - 规范化和标准化 Laravel API 响应数据结构。

485.6k](/packages/guanguans-laravel-api-response)[rap2hpoutre/jacky

Opinionated REST JSON HTTP API client for laravel

174.4k](/packages/rap2hpoutre-jacky)

PHPackages © 2026

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