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

ActiveLibrary

faridibin/laravel-api-response
==============================

A Laravel package for consistently formatted API responses with support for JSON, XML, and YAML.

v2.0.7(8mo ago)112211MITPHPPHP ^8.0

Since Nov 2Pushed 8mo ago1 watchersCompare

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

READMEChangelog (9)Dependencies (2)Versions (18)Used By (0)

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

[](#laravel-api-response)

A Laravel package that provides a standardized, consistent way to format API responses with proper status codes, messages, and error handling.

Features
--------

[](#features)

- Modern PHP 8.0+ implementation with type hints and return types
- Consistent JSON response structure
- Automatic handling of Laravel Models, Collections, and Paginated responses
- Configurable resource naming for collections
- Comprehensive exception handling
- Debug mode with stack traces
- Support for custom headers and messages

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

[](#installation)

Install the package via composer:

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

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

[](#configuration)

Publish the configuration file:

```
php artisan vendor:publish --tag="api-response-config"
```

### Configuration Options

[](#configuration-options)

The `config/api-response.php` file includes:

```
return [
    // Exception handlers
    'exceptions' => [
        ModelNotFoundException::class => [
            'setStatusCode' => 404,
            'setModelNotFoundMessage' => 'Resource not found'
        ],
        ValidationException::class => function($exception, $handler) {
            $handler
                ->setStatusCode(422)
                ->setMessage('Validation failed')
                ->mergeErrors($exception->errors());
        }
    ],

    // Enable stack traces in local environment
    'trace' => env('APP_ENV') === 'local',

    // Use plural resource names for collections
    'resource_name' => true,
];
```

Basic Usage
-----------

[](#basic-usage)

Add the middleware to your API routes in `app/Http/Kernel.php`:

```
protected $middlewareGroups = [
    'api' => [
        \Faridibin\LaravelApiResponse\Http\Middleware\EnsureApiResponse::class,
    ],
];
```

### Response Structure

[](#response-structure)

The package provides a consistent response structure:

```
{
	"data": {},
	"message": "Optional message",
	"errors": [],
	"success": true,
	"status": "success",
	"status_code": 200,
	"status_text": "OK"
}
```

Examples
--------

[](#examples)

### Returning Models

[](#returning-models)

#### Single Model

[](#single-model)

```
public function show(User $user)
{
    return $user;
}
```

Response:

```
{
	"data": {
		"user": {
			"id": 1,
			"name": "Crystal Farrell",
			"email": "berenice.bednar@example.org",
			"email_verified_at": "2025-02-02T02:20:17.000000Z",
			"created_at": "2025-02-02T02:20:17.000000Z",
			"updated_at": "2025-02-02T02:20:17.000000Z"
		}
	},
	"errors": [],
	"success": true,
	"status": "success",
	"status_code": 200,
	"status_text": "OK"
}
```

### Collection Handling

[](#collection-handling)

#### Basic Collection

[](#basic-collection)

```
public function index()
{
    return User::all();
}
```

Response includes automatically pluralized resource name:

```
{
	"data": {
		"users": [
			{
				"id": 1,
				"name": "Crystal Farrell",
				"email": "berenice.bednar@example.org",
				"email_verified_at": "2025-02-02T02:20:17.000000Z",
				"created_at": "2025-02-02T02:20:17.000000Z",
				"updated_at": "2025-02-02T02:20:17.000000Z"
			}
		]
	},
	"success": true,
	"status": "success",
	"status_code": 200,
	"status_text": "OK"
}
```

#### Pagination

[](#pagination)

```
public function index()
{
    return User::paginate();
}
```

Upgrading from laravel-json-response
------------------------------------

[](#upgrading-from-laravel-json-response)

Key changes when upgrading from the previous version:

1. Namespace Change:

    - Old: `Faridibin\LaravelJsonResponse`
    - New: `Faridibin\LaravelApiResponse`
2. Middleware:

    - Old: `OutputJsonResponse`
    - New: `EnsureApiResponse`
3. Trait:

    - Old: `HasJson`
    - New: `HasApiResponse`
4. Method Changes:

    ```
    // Old
    json_response()->error('message');

    // New
    $this->setMessage('message')->mergeErrors(['error']);
    ```

Troubleshooting
---------------

[](#troubleshooting)

### Common Issues

[](#common-issues)

1. Response Not Formatting

    ```
    // Ensure middleware is registered correctly in Kernel.php
    protected $middlewareGroups = [
        'api' => [
            \Faridibin\LaravelApiResponse\Http\Middleware\EnsureApiResponse::class,
        ],
    ];
    ```
2. Resource Names Not Working

    ```
    // Verify config/api-response.php has:
    'resource_name' => true,
    ```
3. Exception Handler Not Working

    ```
    // Check exception configuration:
    'exceptions' => [
        YourException::class => [
            'setStatusCode' => 404,
            'setMessage' => 'Custom message'
        ]
    ]
    ```
4. Stack Traces Not Showing

    - Ensure your environment is set to 'local'
    - Check `trace` config is enabled

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

License
-------

[](#license)

This package is open-sourced software licensed under the MIT license.

###  Health Score

43

—

FairBetter than 91% of packages

Maintenance61

Regular maintenance activity

Popularity21

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity67

Established project with proven stability

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

Recently: every ~54 days

Total

10

Last Release

243d ago

Major Versions

v1.0.1 → v2.0.02025-02-02

PHP version history (2 changes)v1.0PHP &gt;=5.4

v2.0.0PHP ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/899013446321c5d8185df4d616c40b4a08a81017efd04c4b355df90da09197dd?d=identicon)[faridibin](/maintainers/faridibin)

---

Top Contributors

[![faridibin](https://avatars.githubusercontent.com/u/10797272?v=4)](https://github.com/faridibin "faridibin (132 commits)")

### Embed Badge

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

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

###  Alternatives

[getkirby/cms

The Kirby core

1.5k535.5k350](/packages/getkirby-cms)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

595.2M386](/packages/shopware-core)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)

PHPackages © 2026

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