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

ActiveLibrary[API Development](/categories/api)

harrisonratcliffe/laravel-api-responses
=======================================

A Laravel package to easily handle API responses and exceptions

2.2.3(1y ago)0110[4 PRs](https://github.com/harrisonratcliffe/laravel-api-responses/pulls)MITPHPPHP &gt;=7.0CI passing

Since Nov 19Pushed 1mo ago1 watchersCompare

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

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

LARAVEL API RESPONSES
=====================

[](#laravel-api-responses)

 *`composer require harrisonratcliffe/laravel-api-responses`*

 [![license](https://camo.githubusercontent.com/a5876dcbd167ca3daf03358bfcb09ec7848bf2b31a37d24638ead08774acf65c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6861727269736f6e726174636c696666652f6c61726176656c2d6170692d726573706f6e7365733f7374796c653d64656661756c74266c6f676f3d6f70656e736f75726365696e6974696174697665266c6f676f436f6c6f723d776869746526636f6c6f723d303038306666)](https://camo.githubusercontent.com/a5876dcbd167ca3daf03358bfcb09ec7848bf2b31a37d24638ead08774acf65c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6861727269736f6e726174636c696666652f6c61726176656c2d6170692d726573706f6e7365733f7374796c653d64656661756c74266c6f676f3d6f70656e736f75726365696e6974696174697665266c6f676f436f6c6f723d776869746526636f6c6f723d303038306666) [![last-commit](https://camo.githubusercontent.com/0fad4677b8b93b196bf7a1e0641d5b9abca3025a918be1ba0cba02fcea97026a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f6861727269736f6e726174636c696666652f6c61726176656c2d6170692d726573706f6e7365733f7374796c653d64656661756c74266c6f676f3d676974266c6f676f436f6c6f723d776869746526636f6c6f723d303038306666)](https://camo.githubusercontent.com/0fad4677b8b93b196bf7a1e0641d5b9abca3025a918be1ba0cba02fcea97026a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f6861727269736f6e726174636c696666652f6c61726176656c2d6170692d726573706f6e7365733f7374796c653d64656661756c74266c6f676f3d676974266c6f676f436f6c6f723d776869746526636f6c6f723d303038306666) [![repo-top-language](https://camo.githubusercontent.com/b2e38240623b2d0b5c37eec474971dde8d913fc8ff4277fe8f3bcb0db1d34847/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c616e6775616765732f746f702f6861727269736f6e726174636c696666652f6c61726176656c2d6170692d726573706f6e7365733f7374796c653d64656661756c7426636f6c6f723d303038306666)](https://camo.githubusercontent.com/b2e38240623b2d0b5c37eec474971dde8d913fc8ff4277fe8f3bcb0db1d34847/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c616e6775616765732f746f702f6861727269736f6e726174636c696666652f6c61726176656c2d6170692d726573706f6e7365733f7374796c653d64656661756c7426636f6c6f723d303038306666) [![repo-language-count](https://camo.githubusercontent.com/6e231540e506230de394e8d973ff6844abcb41929e041f6b42ab9bbed4f8ae5a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c616e6775616765732f636f756e742f6861727269736f6e726174636c696666652f6c61726176656c2d6170692d726573706f6e7365733f7374796c653d64656661756c7426636f6c6f723d303038306666)](https://camo.githubusercontent.com/6e231540e506230de394e8d973ff6844abcb41929e041f6b42ab9bbed4f8ae5a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c616e6775616765732f636f756e742f6861727269736f6e726174636c696666652f6c61726176656c2d6170692d726573706f6e7365733f7374796c653d64656661756c7426636f6c6f723d303038306666)

🔗 Table of Contents
-------------------

[](#-table-of-contents)

- 📍 [Overview](#-overview)
- 👾 [Features](#-features)
- 🚀 [Getting Started](#-getting-started)
    - ☑️ [Prerequisites](#-prerequisites)
    - ⚙ [Installation](#-installation)
    - 🤖 [Usage](#-usage)
- 🧪 [Testing](#-testing)
- 🔰 [Contributing](#-contributing)
- 🎗 [License](#-license)

---

📍 Overview
----------

[](#-overview)

A Laravel package to easily handle API responses and exceptions.

---

👾 Features
----------

[](#-features)

- 🌟 Return clean, consistent API responses
- 🛡️ Handle API exceptions with standardized error responses
- 🚀 Easy integration with Laravel 7 to 12

---

🚀 Getting Started
-----------------

[](#-getting-started)

### ☑️ Prerequisites

[](#️-prerequisites)

Before getting started with Laravel API Responses, ensure your runtime environment meets the following requirements:

- **Programming Language:** PHP
- **Package Manager:** Composer
- **Laravel Version:** 7 or later

⚙️ Installation
---------------

[](#️-installation)

Install laravel-api-responses using the following method:

1. Install the package via Composer:

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

2. Publish the config with:

```
php artisan vendor:publish --tag="apiresponses-config"
```

### API Exception Handler

[](#api-exception-handler)

*Note: if you use a different API route path than /api you should adjust the below if statement.*

#### Laravel 11-12

[](#laravel-11-12)

To configure the API Exception Handler on Laravel 11-12, add the following configuration to your `boostrap/app.php` file:

```
use Harrisonratcliffe\LaravelApiResponses\ApiExceptionHandler;

->withExceptions(function (Exceptions $exceptions) {
        // your other code here
       $exceptions->render(function (Throwable $exception, $request) {
            if ($request->expectsJson() || $request->is('api/*')) {
                return app(ApiExceptionHandler::class)->renderApiException($exception);
            }
        });
        // your other code here
    })
```

#### Laravel 7-10

[](#laravel-7-10)

To configure the API Exception Handler on Laravel 7-10, add the following configuration inside your render method of your `app/Exceptions/Handler.php` file:

```
use Harrisonratcliffe\LaravelApiResponses\ApiExceptionHandler;

public function render($request, Throwable $exception)
    {
    // your other code here
        if ($request->expectsJson() || $request->is('api/*')) {
            return app(ApiExceptionHandler::class)->renderApiException($exception);
        }
    // your other code here
    }
```

Here's the modified README to reflect the new option for handling internal server error messages:

🔧 Configuration Options
-----------------------

[](#-configuration-options)

The Laravel API Handler package provides a flexible configuration file that allows you to customize default response messages and behaviors. Let's break down each configuration option:

### 🐞 Debug Mode

[](#-debug-mode)

```
'debug_mode' => end('APP_ENV', false),
```

- **Purpose**: Controls whether detailed error information is exposed
- **Default**: Inherits from Laravel's `APP_ENV` environment variable
- **Security Warning**: 🚨 **Only enable in development environments**
- **Behavior**:
    - When `true`: Potentially exposes sensitive error details
    - When `false`: Provides generic, safe error messages

### 📡 Default Success Response

[](#-default-success-response)

```
'success_response' => 'API request processed successfully.',
'success_status_code' => 200,
```

- **Success Message**: Customizable default message for successful API requests
- **Status Code**: Standard HTTP 200 OK response
- **Customization**: Easily modify the default success message to match your application's tone

### 🚧 Default Error Messages

[](#-default-error-messages)

```
'http_not_found' => 'The requested resource or endpoint could not be located.',
'unauthenticated' => 'You must be logged in to access this resource. Please provide valid credentials.',
'model_not_found' => 'The requested resource could not be found. This resource doesn\'t exist.',
'unknown_error' => 'An unexpected error has occurred. Please try again later or contact support if the issue persists.',
```

#### Error Message Breakdown

[](#error-message-breakdown)

- **`http_not_found`**: Used when a requested endpoint doesn't exist
- **`unauthenticated`**: Triggered for unauthorized access attempts
- **`model_not_found`**: Dynamic message for missing database records
    - Provides clarity on what was not found
- **`unknown_error`**: Fallback message for unexpected errors

### ⚠️ Internal Server Error Message

[](#️-internal-server-error-message)

```
'show_500_error_message' => true,
```

- **Purpose**: Controls whether the actual error message from a 500/internal server error is returned.
- **Default**: `true` (actual error message will be shown)
- **Behavior**:
    - When `true`: The detailed error message is returned, which can aid in debugging.
    - When `false`: The `unknown_error` response will be used instead, maintaining user-friendliness.

### 🛠️ Customization Tips

[](#️-customization-tips)

- Modify the config file located at `config/api-responses.php`
- Tailor messages to match your application's voice
- Keep error messages informative but not overly technical
- Ensure messages are user-friendly and provide clear guidance

### 🤖 Usage

[](#-usage)

### Success Responses

[](#success-responses)

```
// In your controller
use Harrisonratcliffe\LaravelApiResponses\Facades\ApiResponses;

public function index()
{
    $data = User::all();
    return ApiResponses::success(
        'Users retrieved successfully',
        $data
    );
}
```

#### Example Success Response

[](#example-success-response)

```
{
    "status": "success",
    "message": "Users retrieved successfully",
    "data": [
        {"id": 1, "name": "John Doe"},
        {"id": 2, "name": "Jane Smith"}
    ]
}
```

### Error Responses

[](#error-responses)

```
use Harrisonratcliffe\LaravelApiResponses\Facades\ApiResponses;

public function store()
{
    return ApiResponses::error(
        'This virtual machine does not exist',
        404,
        [
            'vm_id' => 12345
        ],
        'https://docs.yourapi.com/errors/some-error'
    );
}
```

#### Example Error Response

[](#example-error-response)

```
{
    "status": "error",
    "message": "This virtual machine does not exist",
    "details": {
        "vm_id": 12345
    },
    "documentation": "https://docs.yourapi.com/errors/some-error"
}
```

### Method Signatures

[](#method-signatures)

### `successResponse()`

[](#successresponse)

- `$message` (optional): Custom success message
- `$data` (optional): Response data
- `$statusCode` (optional): HTTP status code (default: 200)

### `errorResponse()`

[](#errorresponse)

- `$message` (required): Error description
- `$statusCode` (optional): HTTP error code (default: 400)
- `$details` (optional) Error details
- `$documentation` (optional): Error documentation link
- `$debug` (optional): Additional debug information

🧪 Testing
---------

[](#-testing)

Run the test suite using the following command: **Using `composer`** [![](https://camo.githubusercontent.com/89abd851ca2ca56bfa482c57e5359d836feeeff46bd2e0ef50108a6fc7e91803/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d3737374242342e7376673f7374796c653d7b62616467655f7374796c657d266c6f676f3d706870266c6f676f436f6c6f723d7768697465)](https://www.php.net/)

```
vendor/bin/pest
```

🔰 Contributing
--------------

[](#-contributing)

Contributions are welcome!

- **🐛 [Report Issues](https://github.com/harrisonratcliffe/laravel-api-responses/issues)**: Submit bugs found or log feature requests for the `laravel-api-responses` project.
- **💡 [Submit Pull Requests](https://github.com/harrisonratcliffe/laravel-api-responses/pulls)**: Review open PRs, and submit your own PRs.

Contributing Guidelines1. **Fork the Repository**: Start by forking the project repository to your github account.
2. **Clone Locally**: Clone the forked repository to your local machine using a git client. ```
    git clone https://github.com/harrisonratcliffe/laravel-api-responses
    ```
3. **Create a New Branch**: Always work on a new branch, giving it a descriptive name. ```
    git checkout -b new-feature-x
    ```
4. **Make Your Changes**: Develop and test your changes locally.
5. **Commit Your Changes**: Commit with a clear message describing your updates. ```
    git commit -m 'Implemented new feature x.'
    ```
6. **Push to github**: Push the changes to your forked repository. ```
    git push origin new-feature-x
    ```
7. **Submit a Pull Request**: Create a PR against the original project repository. Clearly describe the changes and their motivations.
8. **Review**: Once your PR is reviewed and approved, it will be merged into the main branch. Congratulations on your contribution!

Contributor Graph
 [ ![](https://camo.githubusercontent.com/92665005a5383162ed2d0bac9059919407b974f4ed0ebe41cc9d81faa130fedd/68747470733a2f2f636f6e747269622e726f636b732f696d6167653f7265706f3d6861727269736f6e726174636c696666652f6c61726176656c2d6170692d726573706f6e736573) ](https://github.com{/harrisonratcliffe/laravel-api-responses/}graphs/contributors)

---

🎗 License
---------

[](#-license)

This project is protected under the [MIT](https://choosealicense.com/licenses/mit) License. For more details, refer to the [LICENSE](https://github.com/letrixlabs/nodehut-cli/blob/main/LICENSE) file.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance71

Regular maintenance activity

Popularity12

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 83% 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 ~8 days

Recently: every ~1 days

Total

19

Last Release

397d ago

Major Versions

v1.0.5 → 2.0.02025-03-22

PHP version history (2 changes)v1.0.0PHP ^8.1

v1.0.5PHP &gt;=7.0

### Community

Maintainers

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

---

Top Contributors

[![harrisonratcliffe](https://avatars.githubusercontent.com/u/53269265?v=4)](https://github.com/harrisonratcliffe "harrisonratcliffe (112 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (15 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (8 commits)")

---

Tags

apilaravelexceptionsresponseslaravel-api-handlerlaravel-api-responses

###  Code Quality

TestsPest

Static AnalysisRector

Code StyleLaravel Pint

### Embed Badge

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

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

###  Alternatives

[spatie/laravel-fractal

An easy to use Fractal integration for Laravel applications

1.9k15.1M99](/packages/spatie-laravel-fractal)[mollie/laravel-mollie

Mollie API client wrapper for Laravel &amp; Mollie Connect provider for Laravel Socialite

3624.1M28](/packages/mollie-laravel-mollie)[specialtactics/l5-api

Dependencies for the Laravel API Boilerplate package

3672.8k2](/packages/specialtactics-l5-api)

PHPackages © 2026

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