PHPackages                             yousef-ahmed-abdalgawad/laravel-api-responder - 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. yousef-ahmed-abdalgawad/laravel-api-responder

ActiveLibrary[API Development](/categories/api)

yousef-ahmed-abdalgawad/laravel-api-responder
=============================================

Unified JSON API responses for Laravel — standardized success, error, and HTTP exception handling

v1.0.0(today)02↑2900%MITPHPPHP ^8.1

Since Aug 25Pushed todayCompare

[ Source](https://github.com/yousef2002307/laravel-api-responder)[ Packagist](https://packagist.org/packages/yousef-ahmed-abdalgawad/laravel-api-responder)[ RSS](/packages/yousef-ahmed-abdalgawad-laravel-api-responder/feed)WikiDiscussions main Synced today

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

Laravel API Responder
=====================

[](#laravel-api-responder)

[![Latest Version on Packagist](https://camo.githubusercontent.com/90c0e85320e78220db65d7787ddf6aa06cd98fbb61ebb8d372640d3efb4efc8c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f796f757365662d61686d65642d616264616c67617761642f6c61726176656c2d6170692d726573706f6e6465722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/yousef-ahmed-abdalgawad/laravel-api-responder)[![PHP Version](https://camo.githubusercontent.com/cc9cdea9aa96b40a822425e981b0a030e3371202973c7d57b74e8e99834f81dc/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253545382e312d626c7565)](https://www.php.net)[![Laravel Version](https://camo.githubusercontent.com/5b8e585c1631d63a029f7f50b754c8f9a8303cf45ce980700f570cbe5836adf9/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d3131253230253743253230313225323025374325323031332d726564)](https://laravel.com)[![License: MIT](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](https://opensource.org/licenses/MIT)

A lightweight Laravel package that standardizes JSON API responses and handles HTTP exceptions automatically — so every endpoint returns a consistent, predictable structure. easy to use

---

Features
--------

[](#features)

- ✅ Unified JSON response format across all endpoints
- ✅ Trait with helpers for every common HTTP status code
- ✅ Automatic exception handling (401, 403, 404, 405, 422, 429, 500…)
- ✅ Pagination support built-in
- ✅ Laravel auto-discovery — zero manual registration
- ✅ Supports Laravel 11, 12, and 13

---

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

[](#installation)

```
composer require yousef-ahmed-abdalgawad/laravel-api-responder
```

The package is auto-discovered by Laravel. No need to register the service provider manually.

---

Usage
-----

[](#usage)

### 1. ApiResponser Trait

[](#1-apiresponser-trait)

Use the trait in any controller to get access to all response helpers:

```
use YousefAhmedAbdalgawad\ApiResponder\Traits\ApiResponser;

class UserController extends Controller
{
    use ApiResponser;

    public function index()
    {
        $users = User::paginate(10);

        return $this->successResponse(
            $users->items(),
            'Users fetched successfully',
            200,
            [
                'total'        => $users->total(),
                'per_page'     => $users->perPage(),
                'current_page' => $users->currentPage(),
                'last_page'    => $users->lastPage(),
            ]
        );
    }

    public function show(User $user)
    {
        return $this->successResponse($user, 'User found');
    }

    public function destroy(User $user)
    {
        $user->delete();
        return $this->successResponseWithoutData('User deleted successfully');
    }
}
```

### 2. ApiExceptionHandler

[](#2-apiexceptionhandler)

Register the package's exception handler in your `bootstrap/app.php` to automatically handle common HTTP exceptions with a consistent JSON format:

```
use YousefAhmedAbdalgawad\ApiResponder\Exceptions\ApiExceptionHandler;

->withExceptions(function (Exceptions $exceptions): void {
    ApiExceptionHandler::register($exceptions);
})
```

That's it — all API exceptions will now return structured JSON responses automatically.

---

Available Trait Methods
-----------------------

[](#available-trait-methods)

### Success Responses

[](#success-responses)

MethodStatusDescription`successResponse($data, $message, $statusCode, $pagination)``200`Return data with optional pagination`successResponseWithoutData($message, $statusCode)``200`Return message only, no data### Error Responses

[](#error-responses)

MethodStatusDescription`errorResponse($message, $statusCode, $errors)`anyGeneric error with optional errors array`unauthorizedResponse($message)``401`Authentication required`forbiddenResponse($message)``403`Access denied`notFoundResponse($message)``404`Resource not found`methodNotAllowedResponse($message)``405`HTTP method not allowed`conflictResponse($message)``409`Duplicate / conflict`badRequestResponse($message)``400`Bad request`requestEntityTooLargeResponse($message)``413`Payload too large`unsupportedMediaTypeResponse($message)``415`Wrong content type`serverErrorResponse($message)``500`Internal server error`serviceUnavailableResponse($message)``503`Service unavailable---

Automatic Exception Handling
----------------------------

[](#automatic-exception-handling)

When `ApiExceptionHandler::register($exceptions)` is called, the following exceptions are caught and formatted automatically for API requests (`api/*` or `expectsJson()`):

ExceptionStatusMessage`ValidationException``422`First validation error message`ThrottleRequestsException``429`Too many requests + `retry_after` seconds`AuthenticationException``401`Unauthorized`NotFoundHttpException``404`Route not found`MethodNotAllowedHttpException``405`Method not allowed`AccessDeniedHttpException``403`This action is unauthorized`ModelNotFoundException``404`Resource not found`QueryException``409` / `500`Duplicate entry or database error`Throwable` (fallback)`500`Unexpected error---

Response Format
---------------

[](#response-format)

All responses follow this consistent structure:

### Success

[](#success)

```
{
    "status": 200,
    "success": true,
    "message": "Users fetched successfully",
    "data": [...],
    "pagination": {
        "total": 50,
        "per_page": 10,
        "current_page": 1,
        "last_page": 5
    }
}
```

### Error

[](#error)

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

### Rate Limited (429)

[](#rate-limited-429)

```
{
    "status": 429,
    "success": false,
    "message": "Too many requests. Please slow down.",
    "retry_after": 45
}
```

---

Overriding the Exception Handler
--------------------------------

[](#overriding-the-exception-handler)

You can override any specific handler after calling `register()` — Laravel renders exceptions in registration order:

```
->withExceptions(function (Exceptions $exceptions): void {
    // Register package handlers first
    ApiExceptionHandler::register($exceptions);

    // Then override specific ones for your app
    $exceptions->render(function (QueryException $e, $request) {
        // Your custom logic here
    });
})
```

---

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

[](#requirements)

- PHP `^8.1`
- Laravel `^11 | ^12 | ^13`

---

License
-------

[](#license)

The MIT License (MIT). Please see the [LICENSE](LICENSE) file for more information.

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance100

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity42

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://avatars.githubusercontent.com/u/85695400?v=4)[yousef](/maintainers/yousef2002307)[@yousef2002307](https://github.com/yousef2002307)

---

Top Contributors

[![yousef2002307](https://avatars.githubusercontent.com/u/85695400?v=4)](https://github.com/yousef2002307 "yousef2002307 (11 commits)")

---

Tags

responsejsonapilaravelexception

### Embed Badge

![Health badge](/badges/yousef-ahmed-abdalgawad-laravel-api-responder/health.svg)

```
[![Health](https://phpackages.com/badges/yousef-ahmed-abdalgawad-laravel-api-responder/health.svg)](https://phpackages.com/packages/yousef-ahmed-abdalgawad-laravel-api-responder)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.4M354](/packages/psalm-plugin-laravel)[defstudio/telegraph

A laravel facade to interact with Telegram Bots

818355.4k3](/packages/defstudio-telegraph)[api-platform/laravel

API Platform support for Laravel

58190.1k21](/packages/api-platform-laravel)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5226.7k](/packages/simplestats-io-laravel-client)[forjedio/inertia-table

Backend-driven dynamic tables for Laravel + Inertia.js

272.0k](/packages/forjedio-inertia-table)

PHPackages © 2026

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