PHPackages                             i3rror/lapi-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. i3rror/lapi-response

ActiveLibrary[API Development](/categories/api)

i3rror/lapi-response
====================

API Response trait for laravel

v1.3.8(2mo ago)3761↓50%MITPHPPHP &gt;=8.1CI failing

Since Sep 23Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/i3rror/LAPI-response)[ Packagist](https://packagist.org/packages/i3rror/lapi-response)[ RSS](/packages/i3rror-lapi-response/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (11)Versions (32)Used By (0)

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

[](#laravel-api-response)

[![Latest Version](https://camo.githubusercontent.com/be113189305f21e67e33afe6d5a5245404b16611a89310faf9c4494362e59fec/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f762f72656c656173652f693372726f722f4c4150492d726573706f6e7365)](https://github.com/i3rror/LAPI-response/releases)[![GitHub repo size](https://camo.githubusercontent.com/880cd11c777667ffe1cb39831fdd46a0188e2dd376581a5ead73c79c8f247190/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f7265706f2d73697a652f693372726f722f4c4150492d726573706f6e7365)](https://github.com/i3rror/LAPI-response/releases)[![GitHub](https://camo.githubusercontent.com/3c66db7c3bdef650d73cd8f270ed130f8848bca2ff139fa6cc81ce0c1889b40c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f693372726f722f4c4150492d726573706f6e7365)](https://img.shields.io/github/license/i3rror/LAPI-response)[![Packagist Downloads](https://camo.githubusercontent.com/5b08c6ef8fc83d71cd16d3aecbf240a2ec9066805f5f663f2fb8260a728e21cc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f693372726f722f4c4150492d726573706f6e7365)](https://github.com/i3rror/LAPI-response/releases)

Overview
--------

[](#overview)

LAPI-response is a comprehensive Laravel package that standardizes API responses across your application. It provides consistent response formatting, error handling, validation support, and pagination, making it easier to build robust APIs.

Features
--------

[](#features)

- **Consistent JSON Response Format**: Standardized structure for all API responses
- **Multiple Response Types**: Support for success, error, validation, and pagination responses
- **Error Handling**: Built-in error handling with customizable error codes
- **Validation Support**: Simplified request validation with standardized error responses
- **Pagination Support**: Easy pagination with meta information
- **Stream Response**: Support for streaming large datasets
- **Configurable**: Extensive configuration options to customize behavior

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

[](#requirements)

- PHP 8.1 or higher (required for PHP enums)
- Laravel 10.43.0 or higher

Dependencies
------------

[](#dependencies)

This package has been optimized to use the minimal set of Laravel components:

### Core Dependencies

[](#core-dependencies)

- illuminate/config
- illuminate/contracts
- illuminate/http
- illuminate/pagination
- illuminate/support
- illuminate/validation
- symfony/http-foundation
- psr/log

### Optional Dependencies

[](#optional-dependencies)

The following packages are suggested for specific features:

- illuminate/auth - Required for authentication exception handling
- illuminate/container - Required for standalone usage outside of Laravel
- illuminate/routing - Required for redirect functionality
- symfony/http-kernel - Required for HTTP exception handling
- symfony/console - Required for console commands

When used within a Laravel application, these optional dependencies will be available through Laravel itself.

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

[](#installation)

### Step 1: Install via Composer

[](#step-1-install-via-composer)

```
composer require i3rror/lapi-response
```

### Step 2: Register Service Provider

[](#step-2-register-service-provider)

Include the service provider in your `config/app.php` or in `bootstrap/providers.php` if you're using Laravel 11:

```
MA\LaravelApiResponse\Providers\APIResponseProvider::class
```

### Step 3: Publish Configuration

[](#step-3-publish-configuration)

Run the following command to publish the package configuration:

```
php artisan vendor:publish --provider="MA\LaravelApiResponse\Providers\APIResponseProvider" --tag="lapi-response-config"
```

Basic Implementation
--------------------

[](#basic-implementation)

To use this package, add the `APIResponseTrait` to your controllers:

```
use MA\LaravelApiResponse\Traits\APIResponseTrait;

class YourController extends Controller
{
    use APIResponseTrait;

    // Your controller methods...
}
```

You have two implementation options:

1. **Global Implementation**: Add the trait to `App\Http\Controllers\Controller.php` to make it available across all controllers
2. **Local Implementation**: Add the trait only to specific controllers where API responses are needed

### Helper Functions

[](#helper-functions)

Alternatively, you can use the package's global helper functions without adding the trait to your controllers. These functions can be used anywhere in your application:

```
// In any file in your application
return apiOk($data, $message);
return apiNotFound(["Resource not found"], "Resource not found");
return apiResponse(['message' => 'Success', 'data' => $data]);
```

These helper functions can be used as public functions or as internal helper functions within your application's codebase.

Usage Examples
--------------

[](#usage-examples)

### Basic Response

[](#basic-response)

```
return $this->apiResponse([
    'message' => 'Success Message',
    'data' => $yourData,
    'extra' => [
        'field1' => 'Value 1',
        'field2' => 'Value 2'
    ],
]);
```

Response:

```
{
  "status": true,
  "statusCode": 200,
  "timestamp": 1662070087,
  "message": "Success Message",
  "data": {
    "key": "value"
  },
  "field1": "Value 1",
  "field2": "Value 2"
}
```

#### Message Example:

[](#message-example)

```
return $this->apiOk("Operation completed successfully", "Message");
```

Response:

```
{
  "status": true,
  "statusCode": 200,
  "timestamp": 1662104853,
  "message": "Message",
  "data": "Operation completed successfully"
}
```

#### Data Example:

[](#data-example)

```
return $this->apiOk($yourDataArray, "Message");
```

Response:

```
{
  "status": true,
  "statusCode": 200,
  "timestamp": 1662105038,
  "message": "Message",
  "data": [
    {
      "id": 1,
      "name": "Example"
    }
  ]
}
```

### Stream Response

[](#stream-response)

The stream response feature allows you to handle large datasets efficiently:

```
return $this->apiStreamResponse($this->yieldData(), "Streaming data", 200);

protected function yieldData(): Generator
{
    foreach (User::cursor() as $user) {
        yield $user;
    }
}
```

### Error Handling

[](#error-handling)

#### Not Found Example

[](#not-found-example)

```
return $this->apiNotFound("Resource not found", "Error Not Found Message");
```

Response:

```
{
  "status": false,
  "statusCode": 404,
  "timestamp": 1662121027,
  "message": "Not found!",
  "data": null,
  "errors": ["Resource not found"]
}
```

#### Bad Request Example

[](#bad-request-example)

```
return $this->apiBadRequest("Invalid parameters");
```

#### With Error Code

[](#with-error-code)

```
return $this->apiResponse([
    'type' => 'notfound',
    'message' => 'Resource not found',
    'errorCode' => 'RESOURCE_NOT_FOUND',
]);
```

### Available Status Types

[](#available-status-types)

- `created` - 201 Created
- `accepted` - 202 Accepted
- `notfound` - 404 Not Found
- `conflict` - 409 Conflict
- `badrequest` - 400 Bad Request
- `exception` - 422 Unprocessable Entity
- `unauthenticated` - 401 Unauthorized
- `unauthorized` - 401 Unauthorized
- `forbidden` - 403 Forbidden
- `ok` - 200 OK

### Validation Support

[](#validation-support)

```
$data = $this->apiValidate($request, [
    'email' => ['required', 'email'],
    'password' => ['required', 'min:8']
]);
```

If validation fails, it returns a standardized error response with validation errors.

#### Also we have a trait ready to use in case you're using FormRequests.

[](#also-we-have-a-trait-ready-to-use-in-case-youre-using-formrequests)

```
use MA\LaravelApiResponse\Traits\APIRequestValidator;

class UpdateAccountRequest extends FormRequest
{
    use APIRequestValidator;

    // If you want to set a custom message in the return response upon failing
    // You can use this
    protected ?string $errorMessage = 'Validation failed.',
}
```

### Pagination Support

[](#pagination-support)

```
$users = User::paginate(10);
return $this->apiPaginate($users);
```

The response includes pagination metadata with page information and navigation links.

Available Methods
-----------------

[](#available-methods)

All methods listed below are available both as trait methods and as global helper functions. You can use them either way depending on your implementation preference.

### Create Response

[](#create-response)

#### Simplified Usage for apiResponse function

[](#simplified-usage-for-apiresponse-function)

You can use short parameter values in two ways:

- String parameters are set as messages
- Array parameters are set as data

```
// As trait methods
$this->apiResponse($data = null)

// As helper functions
apiResponse($data = null)
```

#### Example

[](#example)

```
return $this->apiResponse([
        'status_code' => Response::HTTP_OK,
        'message' => 'This is custom message',
        'data' => [
            'data1' => 'custom data 1',
            'data2' => 'custom data 2'
        ],
        'extra' => [
            'extra1' => 'extra data 1',
            'extra2' => 'extra data 2'
        ]
    ]);
```

### Response

[](#response)

```
{
  "status": true,
  "statusCode": 200,
  "timestamp": 1749643578,
  "message": "This is custom message",
  "data": {
    "data1": "custom data 1",
    "data2": "custom data 2"
  },
  "extra1": "extra data 1",
  "extra2": "extra data 2"
}
```

### Success Responses

[](#success-responses)

```
// As trait methods
$this->apiOk($data = null)
$this->apiResponse($data = null)

// As helper functions
apiOk($data = null)
apiResponse($data = null)
```

### Error Responses

[](#error-responses)

```
// As trait methods
$this->apiNotFound($errors = null, $throw_exception = true, $errorCode = null, $headers = [])
$this->apiBadRequest($errors = null, $throw_exception = true, $errorCode = null, $headers = [])
$this->apiException($errors = null, $throw_exception = true, $errorCode = null, $headers = [])
$this->apiUnauthenticated($message = null, $errors = null, $errorCode = null, $headers = [])
$this->apiForbidden($message = null, $errors = null, $errorCode = null, $headers = [])

// As helper functions
apiNotFound($errors = null, $throw_exception = true, $errorCode = null, $headers = [])
apiBadRequest($errors = null, $throw_exception = true, $errorCode = null, $headers = [])
apiException($errors = null, $throw_exception = true, $errorCode = null, $headers = [])
apiUnauthenticated($message = null, $errors = null, $errorCode = null, $headers = [])
apiForbidden($message = null, $errors = null, $errorCode = null, $headers = [])
```

### Pagination and Validation

[](#pagination-and-validation)

```
// As trait methods
$this->apiPaginate($pagination, $appends = [], $reverse_data = false, $headers = [])
$this->apiValidate($data, $rules, $messages = [], $attributes = [])

// As helper functions
apiPaginate($pagination, $appends = [], $reverse_data = false, $headers = [])
apiValidate($data, $rules, $messages = [], $attributes = [])
```

### Other Utilities

[](#other-utilities)

```
// As trait methods
$this->apiDD($data) // Debug helper
$this->apiStreamResponse($generator, $message = null, $statusCode = 200, $headers = [])

// As helper functions
apiDD($data) // Debug helper
apiStreamResponse($generator, $message = null, $statusCode = 200, $headers = [])
```

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

[](#configuration)

The package provides extensive configuration options in `config/response.php`:

### Data Handling

[](#data-handling)

```
// Remove null values from arrays
'removeNullDataValues' => false,

// Set empty data to null
'setNullEmptyData' => true,

// Format of validation errors
'returnValidationErrorsKeys' => true,
```

### Error Codes

[](#error-codes)

```
// Enable error codes
'enableErrorCodes' => true,

// Error codes enum class
'errorCodes' => \MA\LaravelApiResponse\Enums\ErrorCodesEnum::class,

// Error codes output format (string or integer)
'errorCodesType' => 'string',

// Return default error codes if not specified
'returnDefaultErrorCodes' => true,
```

### Publishing Error Codes Enum

[](#publishing-error-codes-enum)

```
php artisan lapi-response:publish-error-codes
```

With custom class name:

```
php artisan lapi-response:publish-error-codes CustomErrorCodesEnum
```

Contributors
------------

[](#contributors)

[![Contributors](https://camo.githubusercontent.com/060605c7ebafd8b9013a551dedaf61a9ed92dfb03d0c46583d2073a7245e5972/68747470733a2f2f636f6e747269622e726f636b732f696d6167653f7265706f3d693372726f722f4c4150492d726573706f6e7365)](https://github.com/i3rror/LAPI-response/graphs/contributors)

Testing
-------

[](#testing)

This package includes a comprehensive test suite. To run the tests:

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

### Test Coverage

[](#test-coverage)

The test suite covers:

- Basic API responses (success, error, etc.)
- Pagination functionality
- Validation handling
- Error code handling
- Exception handling
- Helper functions

License
-------

[](#license)

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

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance83

Actively maintained with recent releases

Popularity19

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 66.9% 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 ~59 days

Total

22

Last Release

87d ago

Major Versions

v0.0.1-beta → v1.0.02022-09-23

PHP version history (3 changes)v0.0.1-betaPHP &gt;=7.3

v1.1.0PHP &gt;=8.0

v1.2.0PHP &gt;=8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/1a099d5e79331f6745e5990b1aab9a70b2f157a0287a562e88fa234ee631fa7f?d=identicon)[i3rror](/maintainers/i3rror)

---

Top Contributors

[![Ahmed-Elrayes](https://avatars.githubusercontent.com/u/30704271?v=4)](https://github.com/Ahmed-Elrayes "Ahmed-Elrayes (113 commits)")[![i3rror](https://avatars.githubusercontent.com/u/26237098?v=4)](https://github.com/i3rror "i3rror (55 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

responseapilaravelcmslaravel api responseapi-response

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/i3rror-lapi-response/health.svg)

```
[![Health](https://phpackages.com/badges/i3rror-lapi-response/health.svg)](https://phpackages.com/packages/i3rror-lapi-response)
```

###  Alternatives

[proengsoft/laravel-jsvalidation

Validate forms transparently with Javascript reusing your Laravel Validation Rules, Messages, and FormRequest

1.1k2.3M49](/packages/proengsoft-laravel-jsvalidation)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9682.1M97](/packages/roots-acorn)[andreaselia/laravel-api-to-postman

Generate a Postman collection automatically from your Laravel API

1.0k586.2k3](/packages/andreaselia-laravel-api-to-postman)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)[api-platform/laravel

API Platform support for Laravel

59126.4k6](/packages/api-platform-laravel)

PHPackages © 2026

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