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

ActiveLibrary[API Development](/categories/api)

json-box/laravel-api-response
=============================

A simple and elegant API response formatter for Laravel applications

v1.0.0(4mo ago)31MITPHPPHP ^8.2

Since Jan 5Pushed 4mo agoCompare

[ Source](https://github.com/sanjanarathnyke/laravel-json-response)[ Packagist](https://packagist.org/packages/json-box/laravel-api-response)[ RSS](/packages/json-box-laravel-api-response/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (3)Versions (2)Used By (0)

laravel-json-response
=====================

[](#laravel-json-response)

[![Latest Version](https://camo.githubusercontent.com/fe3cdcf8e2e4f1bf6d47f31e67605752609c71c000685cc792ee452b9271a1a3/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73616e6a616e61726174686e796b652f6c61726176656c2d6a736f6e2d726573706f6e73652e737667)](https://packagist.org/packages/sanjanarathnyke/laravel-json-response)[![License](https://camo.githubusercontent.com/f37dd50188769d0e58a00c9995f1f3494bb64daea36571707ac4955c30a9a154/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f73616e6a616e61726174686e796b652f6c61726176656c2d6a736f6e2d726573706f6e73652e737667)](LICENSE)

A Laravel package designed to enforce a consistent JSON API response structure across applications, improving maintainability and API clarity.

Table of Contents

- [Why use this package](#why-use-this-package)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quick usage](#quick-usage)
- [Response structure](#response-structure)
- [Configuration](#configuration)
- [Customization &amp; extension](#customization--extension)
- [Examples](#examples)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)
- [Credits](#credits)

Why use this package

- Standardizes success, error and paginated JSON responses across your app.
- Removes boilerplate response code from controllers.
- Makes your API predictable and easier to document and consume.

Requirements

- PHP &gt;= 8.0
- Laravel &gt;= 9.x (adjust as necessary for your supported versions)

Installation

1. Install via Composer

```
composer require sanjanarathnyke/laravel-json-response
```

2. (Optional) Publish configuration and assets

If the package provides a config file, publish it with:

```
php artisan vendor:publish --provider="SanjanaRathnyke\LaravelJsonResponse\ServiceProvider" --tag="config"
```

Note: The package supports Laravel package auto-discovery. If auto-discovery is disabled, register the service provider manually in `config/app.php`:

```
'providers' => [
    // ...
    SanjanaRathnyke\LaravelJsonResponse\ServiceProvider::class,
];
```

Quick usage

The package exposes simple helpers/facade methods for returning standardized responses. Replace names below with the actual class/facade/helper names if they differ.

Controller — success response:

```
use Illuminate\Http\JsonResponse;
use SanjanaRathnyke\LaravelJsonResponse\Facades\JsonResponse;

class UserController extends Controller
{
    public function show(User $user): JsonResponse
    {
        return JsonResponse::success($user, 'User retrieved successfully');
    }
}
```

Controller — error response:

```
return JsonResponse::error('Resource not found', 404);
```

Controller — validation error:

```
return JsonResponse::errorValidation($validator->errors(), 'Validation failed', 422);
```

Response structure

Success response example:

```
{
  "success": true,
  "data": { /* resource data */ },
  "message": "Operation successful",
  "meta": {}
}
```

Error response example:

```
{
  "success": false,
  "error": {
    "code": 422,
    "message": "Validation failed",
    "errors": {
      "email": ["The email field is required."]
    }
  }
}
```

Paginated response example:

```
{
  "success": true,
  "data": [ /* items */ ],
  "message": "List of items",
  "meta": {
    "pagination": {
      "total": 100,
      "count": 10,
      "per_page": 10,
      "current_page": 1,
      "total_pages": 10
    }
  }
}
```

Configuration

When published, the configuration (example: `config/jsonresponse.php`) may include options such as:

```
return [
    'keys' => [
        'success' => 'success',
        'data' => 'data',
        'message' => 'message',
        'error' => 'error',
        'meta' => 'meta',
    ],

    'defaults' => [
        'success_message' => 'Operation successful.',
        'error_message' => 'An error occurred.',
        'success_code' => 200,
        'error_code' => 400,
    ],

    'include_debug' => env('APP_DEBUG', false),
];
```

Customization &amp; extension

- Transformers: Use Laravel API Resources or pass transformer callbacks to shape your `data`.
- Global wrapping: Register middleware to wrap all responses automatically.
- Exception handling: In `app/Exceptions/Handler.php` you can call the package's error helper in `render()` or `register()` to ensure all exceptions return the standardized JSON shape.

Examples

Return a paginated collection using a Resource:

```
$users = UserResource::collection(User::paginate(15));

return JsonResponse::success(
    $users,
    'Users list',
    [
        'pagination' => [
            'total' => $users->resource->total(),
            'count' => $users->resource->count(),
            'per_page' => $users->resource->perPage(),
            'current_page' => $users->resource->currentPage(),
            'total_pages' => $users->resource->lastPage(),
        ]
    ]
);
```

Return a custom error payload:

```
return JsonResponse::error(
    'Payment required to access this endpoint',
    402,
    ['policy' => 'upgrade_account']
);
```

Testing

Run the package test suite:

```
composer install
vendor/bin/phpunit
# or if the project uses Pest
vendor/bin/pest
```

Ensure test environment variables are configured (`.env.testing` or `phpunit.xml`) for database and other services used in tests.

Contributing

Contributions are welcome — thank you!

- Fork the repository
- Create a feature branch: git checkout -b feature/your-feature
- Write tests for your change
- Adhere to PSR-12 coding style
- Open a pull request describing your changes

Please open issues for bug reports or feature requests.

License

This project is open source and available under the MIT License. See the LICENSE file for details.

Credits

- Built and maintained by [sanjanarathnyke](https://github.com/sanjanarathnyke)

Notes / Next steps

- If any class names, facade names, helper functions, publish tags, or the configuration file differ from the examples above, tell me the exact names and I will update this README to match the code in your repository.
- If you want, I can create a PR that replaces the existing README with this version — tell me and provide any additional clarifications (supported Laravel/PHP versions, exact usage examples) and I will prepare the PR.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance75

Regular maintenance activity

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

Unknown

Total

1

Last Release

133d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/c539d2d3470c99a1796c4425a73f253546bf1dd3a6c300aac1f76af20cabab0f?d=identicon)[sanjana](/maintainers/sanjana)

---

Top Contributors

[![sanjanarathnyke](https://avatars.githubusercontent.com/u/138987781?v=4)](https://github.com/sanjanarathnyke "sanjanarathnyke (3 commits)")

---

Tags

responsejsonformatterapilaravel

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[obiefy/api-response

Simple Laravel package to return Json responses.

17324.6k](/packages/obiefy-api-response)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)[djurovicigoor/larajsonresponse

Laravel API wrapper for returning JSON response.

116.8k](/packages/djurovicigoor-larajsonresponse)[nilportugues/laravel5-json-api-dingo

Laravel5 JSONAPI and Dingo together to build APIs fast

311.5k](/packages/nilportugues-laravel5-json-api-dingo)[nicklaw5/larapi

A simple Laravel 5 class for handling json api responses.

111.5k](/packages/nicklaw5-larapi)

PHPackages © 2026

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