PHPackages                             src83/laravel-api-response - 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. src83/laravel-api-response

ActiveLibrary[API Development](/categories/api)

src83/laravel-api-response
==========================

Unified REST API Response formatter for Laravel with exception handling, localization, logging, and pagination

v1.0.0(today)00MITPHPPHP ^8.2CI passing

Since Jul 31Pushed todayCompare

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

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

Unified REST API Response formatter for Laravel
===============================================

[](#unified-rest-api-response-formatter-for-laravel)

`LaravelApiResponse` is a [Laravel](https://laravel.com/) package for building consistent and well-structured REST API JSON responses. Includes automatic exception handling, module-aware localization, structured logging, and pagination out of the box.

[![Tests](https://github.com/src83/laravel-api-response/actions/workflows/tests.yml/badge.svg)](https://github.com/src83/laravel-api-response/actions/workflows/tests.yml)[![Code Style](https://github.com/src83/laravel-api-response/actions/workflows/pint.yml/badge.svg)](https://github.com/src83/laravel-api-response/actions/workflows/pint.yml)[![Static Analysis](https://github.com/src83/laravel-api-response/actions/workflows/phpstan.yml/badge.svg)](https://github.com/src83/laravel-api-response/actions/workflows/phpstan.yml)[![Latest Stable Version](https://camo.githubusercontent.com/47859cab694684761be6964514c6adeb4a45f826fab2c574458ef3384c9e7b18/68747470733a2f2f706f7365722e707567782e6f72672f73726338332f6c61726176656c2d6170692d726573706f6e73652f76)](https://packagist.org/packages/src83/laravel-api-response)[![License](https://camo.githubusercontent.com/b1a758512d0b1c42abebd815f0a526348e74190aa0555db446d3d65662178f68/68747470733a2f2f706f7365722e707567782e6f72672f73726338332f6c61726176656c2d6170692d726573706f6e73652f6c6963656e7365)](LICENSE.md)

**Available in other languages:** [RU](docs/ru/README.md)

---

Table of contents
-----------------

[](#table-of-contents)

- [Introduction](#introduction)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quick start](#quick-start)
- [Features](#features)
- [Design principles](#design-principles)
- [Documentation](#documentation)
- [Changelog](CHANGELOG.md)
- [License](#license)

---

Introduction
------------

[](#introduction)

Every Laravel API developer has hit the same wall: an exception fires, and instead of JSON your client gets a wall of HTML. `laravel-api-response` fixes that — and while it's at it, gives every response a consistent, predictable structure your frontend can always rely on.

Every response carries a structured `message` object with a machine-readable `key` and a human-readable `gui` string resolved from your translation files. Errors additionally include a `sys` field for internal context.

**Success response example:**

```
{
    "success": true,
    "http_code": 201,
    "http_text": "Created",
    "message": {
        "key": "user.created",
        "gui": "User created successfully"
    },
    "meta": null,
    "data": {
        "id": 42,
        "email": "user@example.com"
    }
}
```

**Error response example** (including exceptions — always JSON, never HTML):

```
{
    "success": false,
    "http_code": 422,
    "http_text": "Unprocessable Content",
    "message": {
        "key": "user.unprocessable_content",
        "gui": "Validation error",
        "sys": "The email field is required"
    },
    "details": {
        "fields": {
            "email": ["The email field is required."]
        }
    }
}
```

`data` and `details` are mutually exclusive — `data` and `meta` appears in **success** responses, `details` in **errors**. `meta` is `null` for simple responses and carries pagination data when the response is paginated.

Requirements
------------

[](#requirements)

VersionsPHP8.2 or higherLaravel9, 10, or 11Installation
------------

[](#installation)

**1. Require the package:**

```
composer require src83/laravel-api-response
```

**2. Run the installer:**

```
php artisan api-response:install
```

The installer adds some things and modifies others in your existing project. You can review these targeted changes by running `git status` after executing the installation command.

In particular, pay close attention to `Handler.php` and `Authenticate.php`.

This package can be installed both on a fresh Laravel application and on an existing project with substantial business logic and a customized exception handler.

Depending on the project, the installer may behave differently (adaptively):

- In a new, clean Laravel project, these two files will be fully updated during installation. However, they still require a quick review before you accept the changes. Once the installation is complete, you can immediately proceed to the next step `Verify the installation` to make sure the package was installed correctly.
- When installing the package into a more mature project, `Handler.php` and `Authenticate.php` may not be updated immediately if the installer detects that they already contain customized logic. Such items will be marked as `ACTION REQUIRED`. This is normal behavior. In any case, proceed to the next step `Verify the installation`.

**3. Verify the installation:**

```
php artisan api-response:check
```

Confirms that all components have been installed correctly.
If anything shows `ACTION REQUIRED`, the installer detected existing custom logic in that file and did not overwrite it automatically.

In this case:

- Back up the files marked `ACTION REQUIRED`;
- Force-update them by running: ```
    php artisan api-response:check --fix
    ```
- Manually resolve any conflicts between the existing and new logic in the updated files.

That's it — the package is installed and ready to use.
You can run `php artisan api-response:check` one more time to confirm, then get to the fun part.

Quick start
-----------

[](#quick-start)

```
use Src83\LaravelApiResponse\Enums\MessageKeyEnum;
use Src83\LaravelApiResponse\Http\Responses\ApiErrorResponse;
use Src83\LaravelApiResponse\Http\Responses\ApiSuccessResponse;
use Symfony\Component\HttpFoundation\Response;

// List — no messageKey needed
return ApiSuccessResponse::make(data: UserResource::collection($users));

// Store
return ApiSuccessResponse::make(
    data: new UserResource($user),
    httpCode: Response::HTTP_CREATED,
    messageKey: MessageKeyEnum::CREATED,
);

// Error
return ApiErrorResponse::make(
    httpCode: Response::HTTP_NOT_FOUND,
    messageKey: 'user.not_found',
    sysMessage: $e->getMessage(),
);
```

For a full reference — call signatures, response shapes, and pagination — see the [docs/api-contract.md](docs/api-contract.md)

Features
--------

[](#features)

- **Consistent JSON contract** — every response, including exceptions, returns the same structure
- **Exception → JSON** — HTTP and domain exceptions are caught and rendered as structured errors, never as HTML
- **Module-aware localization** — `gui` messages are resolved from `lang/{locale}/api_response.php` by module and key
- **Pagination** — built-in `ApiPaginator` for Eloquent paginators and `ArrayPaginator` for plain arrays
- **Structured logging** — separate channels for throwable errors, rendered errors, missing translations, and business warnings
- **Middleware stack** — `ForceAcceptJson`, `BindRequestContext` (request ID), `WrapApiResponse`, `AppendExecutionTimeMeta`, `ForceContentType`
- **Execution time** — optional `meta.execution_time` field for diagnosing slow endpoints
- **Artisan commands** — `api-response:install` and `api-response:check [--fix]`
- **Built-in exceptions** — `DomainLayerException` and `ItemNotFoundException` ready to throw from your domain layer
- **Request macros** — `$request->isApi()` and `$request->apiModule()` available out of the box
- **Standard action vocabulary** — `MessageKeyEnum` covers all common CRUD and status keys

Design principles
-----------------

[](#design-principles)

- Controllers don't build messages — they pass a `messageKey`, the package resolves the translation
- `messageKey` can be a `MessageKeyEnum` value, a plain string, or a compound `module.key`
- The module is derived automatically from the route prefix — no manual configuration needed per endpoint
- All exceptions speak the same JSON — no special cases, no HTML leaking through

Documentation
-------------

[](#documentation)

> The essentials are covered in this README. Full documentation is in progress — for details, browse the inline code comments or [open an issue](https://github.com/src83/laravel-api-response/issues).

- Installation → [docs/installation.md](docs/installation.md)
- API reference (contract + usage examples) → [docs/api-contract.md](docs/api-contract.md)
- Configuration reference → [docs/configuration.md](docs/configuration.md)
- Localization → [docs/localization.md](docs/localization.md)
- Logging → [docs/logging.md](docs/logging.md)
- Exception handling → [docs/exceptions.md](docs/exceptions.md)

License
-------

[](#license)

- Written and copyrighted © 2026 by [Roman Staroseltsev](https://github.com/src83)
- Open-source software licensed under the [MIT license](LICENSE.md)
- Author: [LinkedIn](https://linkedin.com/in/staroseltsev)

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance100

Actively maintained with recent releases

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

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

Unknown

Total

1

Last Release

0d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/83b1765cff683bd18e5649fa06b8919020aca98b1c10ea96fd961249de036be1?d=identicon)[src83](/maintainers/src83)

---

Top Contributors

[![src83](https://avatars.githubusercontent.com/u/5196583?v=4)](https://github.com/src83 "src83 (69 commits)")

---

Tags

apiapi-exceptionsapi-loggerapi-responseexceptionformatterjsonlaravellaravel-packagelocalizationmiddlewarepaginationrest-apijsonformattermiddlewareapilaravellocalizationpaginationexceptionlaravel-packageREST APIapi exceptionsapi-responseapi-logger

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[nuwave/lighthouse

A framework for serving GraphQL from Laravel

3.5k12.2M121](/packages/nuwave-lighthouse)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9872.4M139](/packages/roots-acorn)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

78727.1M203](/packages/laravel-mcp)[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.5k30.2M153](/packages/laravel-cashier)[yajra/laravel-oci8

Oracle DB driver for Laravel via OCI8

8793.3M26](/packages/yajra-laravel-oci8)[laravel/scout

Laravel Scout provides a driver based solution to searching your Eloquent models.

1.7k57.2M655](/packages/laravel-scout)

PHPackages © 2026

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