PHPackages                             ifar/laravel-api-responses - 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. ifar/laravel-api-responses

ActiveLibrary[API Development](/categories/api)

ifar/laravel-api-responses
==========================

A simple, consistent JSON API response standard for Laravel applications.

v0.2.0(4mo ago)00MITPHPPHP ^8.1

Since Feb 9Pushed 4mo agoCompare

[ Source](https://github.com/Ifar-Solutions/laravel-api-responses)[ Packagist](https://packagist.org/packages/ifar/laravel-api-responses)[ RSS](/packages/ifar-laravel-api-responses/feed)WikiDiscussions main Synced today

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

Laravel API Responses
=====================

[](#laravel-api-responses)

 [ ![Latest Version](https://camo.githubusercontent.com/90a2b2233d24b5a5ca4f28b4df9ee4ebf6e71c50718fa23797f4e93803885296/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696661722f6c61726176656c2d6170692d726573706f6e7365732e737667) ](https://packagist.org/packages/ifar/laravel-api-responses) [ ![Total Downloads](https://camo.githubusercontent.com/e0c4ffa58d8f8f0b27e9a8e898bc6fe2c828d0a90b184f3c74888228dffd7652/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f696661722f6c61726176656c2d6170692d726573706f6e7365732e737667) ](https://packagist.org/packages/ifar/laravel-api-responses) [ ![License](https://camo.githubusercontent.com/65f400a87b221ec692cd16c665500f7e0dcd4a1b6fd07a2b960429c6bbb7d002/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f496661722d536f6c7574696f6e732f6c61726176656c2d6170692d726573706f6e7365732e737667) ](https://github.com/Ifar-Solutions/laravel-api-responses/blob/main/LICENSE)

A simple, consistent JSON API response standard for Laravel applications.

This package helps you return clean, predictable JSON responses for success and error cases without repeating boilerplate code.

---

Features
--------

[](#features)

- Unified success responses
- Unified error responses and `fail()` alias
- Pagination helper (standard format with meta)
- Validation error formatting
- Exception handler integration helper
- Optional controller trait
- Response macros (`response()->apiSuccess()`, etc.)
- Configurable response keys and default messages
- Lightweight and framework-friendly

---

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

[](#requirements)

- PHP 8.1 or higher
- Laravel 9, 10, or 11

---

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

[](#installation)

Install the package via Composer:

```
composer require ifar/laravel-api-responses
```

Publish the configuration file (optional):

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

---

Default Response Format
-----------------------

[](#default-response-format)

### Success response

[](#success-response)

```
{
  "success": true,
  "message": "Operation successful",
  "data": {},
  "meta": null
}
```

### Error response

[](#error-response)

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

---

Usage
-----

[](#usage)

### Using the ApiResponse class

[](#using-the-apiresponse-class)

```
use Ifar\ApiResponses\ApiResponse;

return ApiResponse::success($data, 'User created');
```

```
return ApiResponse::error('Unauthorized', 401);
return ApiResponse::fail('Not found', 404);  // alias for error()
```

### Pagination

[](#pagination)

Return paginated data with pagination meta in the standard format:

```
use Ifar\ApiResponses\ApiResponse;

$users = User::paginate(15);
return ApiResponse::paginated($users, 'Users retrieved');
```

Response includes `data` (items) and `meta` (current\_page, last\_page, per\_page, total, from, to).

### Validation errors

[](#validation-errors)

Format Laravel's `ValidationException` into your standard error response (e.g. in your exception handler or when catching validation failures):

```
use Ifar\ApiResponses\ApiResponse;
use Illuminate\Validation\ValidationException;

// In exception handler or when catching ValidationException:
return ApiResponse::validationFailed($e);
```

Response (status 422):

```
{
  "success": false,
  "message": "The given data was invalid.",
  "errors": {
    "email": ["The email field is required."],
    "name": ["The name field must be at least 2 characters."]
  }
}
```

### Exception handler integration

[](#exception-handler-integration)

Use `fromException()` in your exception handler to return this package’s format for `ValidationException` (and fall back to your default for others):

```
use Ifar\ApiResponses\ApiResponse;

// In App\Exceptions\Handler (or bootstrap/app.php exception handler)
public function register(): void
{
    $this->renderable(function (Throwable $e, Request $request) {
        if ($request->expectsJson() && $response = ApiResponse::fromException($e)) {
            return $response;
        }
    });
}
```

### Response macros

[](#response-macros)

You can use the `response()` helper with macros instead of the `ApiResponse` class:

```
return response()->apiSuccess($data, 'Created');
return response()->apiError('Not found', 404);
return response()->apiFail('Forbidden', 403);       // alias
return response()->apiValidationFailed($e);
return response()->apiPaginated($paginator, 'List');
```

---

### Using the ApiResponds trait (recommended)

[](#using-the-apiresponds-trait-recommended)

```
use Ifar\ApiResponses\Traits\ApiResponds;
use Illuminate\Validation\ValidationException;

class UserController extends Controller
{
    use ApiResponds;

    public function store()
    {
        return $this->success($user, 'User created');
    }

    public function index()
    {
        return $this->paginated(User::paginate(15), 'Users list');
    }

    public function update(Request $request, User $user)
    {
        try {
            $validated = $request->validate([...]);
        } catch (ValidationException $e) {
            return $this->validationFailed($e);
        }
        // ...
    }
}
```

Trait methods: `success()`, `error()`, `fail()`, `paginated()`, `validationFailed()`.

---

Configuration
-------------

[](#configuration)

You may customize the response structure and default messages. Config uses plural groups for future expansion:

```
return [
    'keys' => [
        'success_key' => 'success',
        'message_key' => 'message',
        'data_key'    => 'data',
        'errors_key'  => 'errors',
        'meta_key'    => 'meta',
    ],

    'defaults' => [
        'success_message' => '',
        'error_message'   => 'An error occurred.',
    ],
];
```

When you pass an empty string for `message` to `success()` or `error()`, the corresponding default from `defaults` is used.

---

Testing
-------

[](#testing)

```
composer install
./vendor/bin/phpunit
```

---

When to use this package
------------------------

[](#when-to-use-this-package)

- Building REST APIs
- Maintaining consistent response formats
- Reducing repeated response boilerplate
- Team-based or long-term projects

---

License
-------

[](#license)

MIT

###  Health Score

30

—

LowBetter than 62% of packages

Maintenance74

Regular maintenance activity

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity34

Early-stage or recently created project

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

Total

2

Last Release

144d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/250619116?v=4)[Abdulla Farhaan](/maintainers/farhaanabdulla)[@farhaanabdulla](https://github.com/farhaanabdulla)

---

Top Contributors

[![farhaanabdulla](https://avatars.githubusercontent.com/u/250619116?v=4)](https://github.com/farhaanabdulla "farhaanabdulla (2 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ifar-laravel-api-responses/health.svg)

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

###  Alternatives

[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77022.3M151](/packages/laravel-mcp)[propaganistas/laravel-disposable-email

Disposable email validator

6023.0M6](/packages/propaganistas-laravel-disposable-email)[nuwave/lighthouse

A framework for serving GraphQL from Laravel

3.5k11.8M117](/packages/nuwave-lighthouse)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M345](/packages/psalm-plugin-laravel)[laravel/ai

The official AI SDK for Laravel.

1.0k3.2M194](/packages/laravel-ai)[defstudio/telegraph

A laravel facade to interact with Telegram Bots

816333.6k3](/packages/defstudio-telegraph)

PHPackages © 2026

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