PHPackages                             nurbekjummayev/laravel-api-response-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. [API Development](/categories/api)
4. /
5. nurbekjummayev/laravel-api-response-helpers

ActiveLibrary[API Development](/categories/api)

nurbekjummayev/laravel-api-response-helpers
===========================================

A Laravel package for standardized API responses

1.2(3w ago)0120↓46.7%2MITPHPPHP ^8.1CI passing

Since Jan 10Pushed 3w agoCompare

[ Source](https://github.com/nurbekjummayev/laravel-api-response-helpers)[ Packagist](https://packagist.org/packages/nurbekjummayev/laravel-api-response-helpers)[ Docs](https://github.com/NurbekJummayev/laravel-api-response-helpers)[ RSS](/packages/nurbekjummayev-laravel-api-response-helpers/feed)WikiDiscussions main Synced today

READMEChangelog (5)Dependencies (21)Versions (6)Used By (2)

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

[](#laravel-api-response-helpers)

A Laravel package for standardized API responses with helpful exceptions.

Installation
------------

[](#installation)

Install the package via composer:

```
composer require nurbekjummayev/laravel-api-response-helpers
```

Usage
-----

[](#usage)

### Helper Functions

[](#helper-functions)

The package provides convenient helper functions for common HTTP responses:

#### Success Responses

[](#success-responses)

```
// List with pagination
public function index(Request $request)
{
    $query = Product::query();
    $data = $query->paginate($request->get('per_page', 10));

    return okWithPaginateResponse($data);
}

// Show single resource
public function show(int $id)
{
    $model = Product::findOrFail($id);

    return okResponse($model);
}

// Create resource
public function store(Request $request)
{
    $model = Product::create($request->all());

    return createdResponse($model);
}

// Update resource
public function update(Request $request, int $id)
{
    $model = Product::findOrFail($id);
    $model->update($request->all());

    return okResponse($model);
}

// Delete resource
public function destroy(int $id)
{
    $model = Product::findOrFail($id);
    $model->delete();

    return okResponse($model);
}
```

#### Error Responses

[](#error-responses)

```
// Validation error (422)
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
    return invalidData('Validation failed', ['errors' => $validator->errors()]);
}

// Not found (404)
$model = Product::find($id);
if (!$model) {
    return notFoundRequestResponse('Product not found');
}

// Unauthorized (401)
if (!auth()->check()) {
    return unauthorizedRequestResponse();
}

// Forbidden (403)
if (!auth()->user()->can('update', $model)) {
    return forbiddenRequestResponse('Access denied');
}

// Bad request (400)
if (!$request->has('required_field')) {
    return badRequestResponse('Missing required field');
}

// Method not allowed (405)
return methodNotAllowedRequestResponse();

// Payload too large (413)
return postTooLargeResponse();

// Too many requests (429)
return tooManyRequestsResponse();

// Server error (500)
try {
    // Some operation
} catch (\Exception $e) {
    return serverErrorResponse('Something went wrong');
}

// Any custom status
return errorResponse('Custom error', httpStatus: 418, errorMsg: 'TEAPOT');
```

#### Custom Response

[](#custom-response)

```
return apiResponse(
    msg: 'Custom message',
    data: ['key' => 'value'],
    success: true,
    httpStatus: 200,
    errorMsg: null,
    extraData: ['meta' => ['version' => '1.0']]
);
```

### Exceptions

[](#exceptions)

The package provides exception classes that automatically render as JSON responses:

```
use NurbekJummayev\ApiResponseHelper\Exceptions\NotFoundException;
use NurbekJummayev\ApiResponseHelper\Exceptions\ForbiddenException;
use NurbekJummayev\ApiResponseHelper\Exceptions\ValidationException;

// Not Found Exception
public function show(int $id)
{
    $model = Product::find($id);

    if (!$model) {
        throw new NotFoundException('Product not found', ['product_id' => $id]);
    }

    return okResponse($model);
}

// Validation Exception
public function store(Request $request)
{
    $validator = Validator::make($request->all(), $rules);

    if ($validator->fails()) {
        throw new ValidationException(
            message: 'Validation failed',
            data: ['errors' => $validator->errors()]
        );
    }

    $model = Product::create($request->all());
    return createdResponse($model);
}

// Forbidden Exception
public function update(Request $request, int $id)
{
    $model = Product::findOrFail($id);

    if (!auth()->user()->can('update', $model)) {
        throw new ForbiddenException('You cannot update this product');
    }

    $model->update($request->all());
    return okResponse($model);
}
```

#### Available Exceptions

[](#available-exceptions)

- `ApiResponseException` - Base exception class
- `BadRequestException` - 400
- `UnauthorizedException` - 401
- `ForbiddenException` - 403
- `NotFoundException` - 404
- `MethodNotAllowedException` - 405
- `PostTooLargeException` - 413
- `ValidationException` - 422
- `TooManyRequestsException` - 429
- `ServerErrorException` - 500

> **Note:** `ValidationException` shares its short name with Laravel's own `Illuminate\Validation\ValidationException`. If you need both in the same file, import this package's class with an alias:
>
> ```
> use NurbekJummayev\ApiResponseHelper\Exceptions\ValidationException as ApiValidationException;
> ```

### Response Format

[](#response-format)

All responses follow a consistent structure:

**Standard Response:**

```
{
  "msg": "Success message",
  "error": null,
  "success": true,
  "data": {}
}
```

**Paginated Response:**

```
{
  "msg": "OK",
  "error": null,
  "success": true,
  "data": [
    {
      "id": 1,
      "name": "Product 1"
    },
    {
      "id": 2,
      "name": "Product 2"
    }
  ],
  "meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 5,
    "per_page": 15,
    "to": 15,
    "total": 75
  }
}
```

`okWithPaginateResponse()` supports all three Laravel paginators:

- `paginate()` — full `meta` as shown above.
- `simplePaginate()` — `meta` with `current_page`, `from`, `per_page`, `to`, `has_more` (no `total`/`last_page`).
- `cursorPaginate()` — `meta` with `per_page`, `next_cursor`, `prev_cursor`.

**With Extra Data:**

```
{
  "msg": "Success",
  "error": null,
  "success": true,
  "data": {},
  "custom_key": "custom_value"
}
```

AI Support (Laravel Boost)
--------------------------

[](#ai-support-laravel-boost)

This package ships first-class AI support for [Laravel Boost](https://laravel.com/docs/boost). When a project that uses Boost installs this package, the guidelines and an agent skill are discovered automatically.

What's included:

- **Guideline** — `resources/boost/guidelines/core.blade.php`: a short, always-loaded overview of the response envelope and helpers.
- **Skill** — `resources/boost/skills/api-response-helper/SKILL.md`: the full `api-response-helper` skill, loaded on demand when an agent works on API responses.

In a consuming project that already has Boost installed:

```
composer require nurbekjummayev/laravel-api-response-helpers

# Discover and publish this package's guidelines + skill
php artisan boost:install
# or, for an existing Boost setup:
php artisan boost:update --discover
```

Boost then teaches the coding agent (Claude Code, Cursor, Copilot, etc.) to use `okResponse()`, `okWithPaginateResponse()`, the error helpers, and the renderable exceptions correctly. No configuration is required — discovery is based on the `resources/boost/` directory.

Testing
-------

[](#testing)

```
composer test
```

Code Quality
------------

[](#code-quality)

```
# Format code
composer format

# Test coverage
composer test-coverage
```

License
-------

[](#license)

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

###  Health Score

44

—

FairBetter than 90% of packages

Maintenance95

Actively maintained with recent releases

Popularity14

Limited adoption so far

Community10

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

Total

5

Last Release

23d ago

Major Versions

0.1.1 → 1.12026-03-24

PHP version history (2 changes)0.1.0PHP ^8.0|^8.1|^8.2|^8.3

1.2PHP ^8.1

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/82907151?v=4)[Nurbek](/maintainers/nurbekJummayev)[@nurbekjummayev](https://github.com/nurbekjummayev)

---

Top Contributors

[![nurbekjummayev](https://avatars.githubusercontent.com/u/82907151?v=4)](https://github.com/nurbekjummayev "nurbekjummayev (10 commits)")

---

Tags

responsejsonapilaravelhelper

###  Code Quality

TestsPest

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[defstudio/telegraph

A laravel facade to interact with Telegram Bots

816333.9k3](/packages/defstudio-telegraph)[dedoc/scramble

Automatic generation of API documentation for Laravel applications.

2.1k11.2M102](/packages/dedoc-scramble)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5022.0k](/packages/simplestats-io-laravel-client)[api-platform/laravel

API Platform support for Laravel

58171.8k14](/packages/api-platform-laravel)[rawilk/profile-filament-plugin

Profile &amp; MFA starter kit for filament.

3914.6k](/packages/rawilk-profile-filament-plugin)

PHPackages © 2026

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