PHPackages                             hiteshpadhara/laravel-response-macro - 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. hiteshpadhara/laravel-response-macro

ActiveLibrary[API Development](/categories/api)

hiteshpadhara/laravel-response-macro
====================================

Adds a Response::api() macro for uniform JSON APIs

00PHPCI passing

Since Mar 1Pushed 2mo ago1 watchersCompare

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

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel Response Macro
======================

[](#laravel-response-macro)

[![Latest Version](https://camo.githubusercontent.com/fcb56362f5dae86dafec4151bbf108440a06ee5b9f5b8fb6bc0c743a2e345181/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f686974657368706164686172612f6c61726176656c2d726573706f6e73652d6d6163726f2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hiteshpadhara/laravel-response-macro)[![Total Downloads](https://camo.githubusercontent.com/b9f0fde6c6e82733b4c7b8748f07bd190e9327607eb15e2ffef2e1c51a1a0f44/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f686974657368706164686172612f6c61726176656c2d726573706f6e73652d6d6163726f2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/hiteshpadhara/laravel-response-macro)[![Build Status](https://camo.githubusercontent.com/3e45b1b70916fb087887f2fd4ab642d3f737bdb97e96ba56197b5a78ff2ff9f6/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f686974657368706164686172612f6c61726176656c2d726573706f6e73652d6d6163726f2f74657374732e796d6c3f6272616e63683d6d61696e267374796c653d666c61742d737175617265)](https://github.com/hiteshpadhara/laravel-response-macro/actions)[![License](https://camo.githubusercontent.com/d9e49921b1a5c7ca190d43509cca0f35bf4d2df758ad807d186630bcd2d40237/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f686974657368706164686172612f6c61726176656c2d726573706f6e73652d6d6163726f2e7376673f7374796c653d666c61742d737175617265)](LICENSE)

> A simple, elegant way to create uniform JSON API responses in Laravel. Provides helper methods, exception handling, pagination support, and testing traits.

Features
--------

[](#features)

- Uniform JSON response structure for all API endpoints
- Convenient helper methods for common HTTP status codes
- Automatic validation error formatting
- Built-in exception handler for API responses
- Laravel Paginator support with meta and links
- PHPUnit testing traits for easier API testing
- Configurable response keys
- Laravel 10 and 11 support

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

[](#installation)

Install the package via Composer:

```
composer require hiteshpadhara/laravel-response-macro
```

The service provider will be auto-registered for Laravel 10+.

Usage
-----

[](#usage)

### Basic Response

[](#basic-response)

```
use Illuminate\Support\Facades\Response;

return Response::api(200, 'Success', ['user' => $user]);
```

**Response:**

```
{
  "status": 200,
  "message": "Success",
  "data": {
    "user": { "id": 1, "name": "John" }
  }
}
```

### Helper Methods

[](#helper-methods)

```
// Success (200)
return Response::apiSuccess($data, 'Operation successful');

// Created (201)
return Response::apiCreated($resource, 'User created successfully');

// Accepted (202)
return Response::apiAccepted(null, 'Request accepted for processing');

// No Content (204)
return Response::apiNoContent();

// Not Found (404)
return Response::apiNotFound('User not found');

// Unauthorized (401)
return Response::apiUnauthorized('Please log in');

// Forbidden (403)
return Response::apiForbidden('Access denied');

// Too Many Requests (429)
return Response::apiTooManyRequests('Rate limit exceeded');

// Server Error (500)
return Response::apiServerError('Something went wrong');
```

### Validation Errors

[](#validation-errors)

```
// With a Validator instance
return Response::apiValidationError($validator);

// Or with an errors array
return Response::apiValidationError([
    'email' => ['Email is required'],
    'password' => ['Password must be at least 8 characters']
]);
```

**Response:**

```
{
  "status": 422,
  "message": "The given data was invalid.",
  "errors": {
    "email": ["Email is required"],
    "password": ["Password must be at least 8 characters"]
  }
}
```

### Custom Error Responses

[](#custom-error-responses)

```
return Response::apiError('Custom error message', 418, ['details' => 'I\'m a teapot']);
```

### Pagination Support

[](#pagination-support)

When you pass a Laravel paginator, it automatically includes meta and links:

```
$users = User::paginate(15);
return Response::apiSuccess($users);
```

**Response:**

```
{
  "status": 200,
  "message": "Success",
  "data": [
    { "id": 1, "name": "John" },
    { "id": 2, "name": "Jane" }
  ],
  "meta": {
    "current_page": 1,
    "per_page": 15,
    "total": 100,
    "last_page": 7
  },
  "links": {
    "first": "https://example.com/users?page=1",
    "last": "https://example.com/users?page=7",
    "prev": null,
    "next": "https://example.com/users?page=2"
  }
}
```

Exception Handling
------------------

[](#exception-handling)

Add the trait to your exception handler to automatically convert exceptions to JSON API responses:

```
namespace App\Exceptions;

use Hiteshpadhara\ResponseMacro\HandlesApiExceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    use HandlesApiExceptions;

    // All exceptions will now return JSON responses
}
```

**Supported Exceptions:**

- `AuthenticationException` → 401
- `ModelNotFoundException` → 404
- `NotFoundHttpException` → 404
- `ValidationException` → 422
- `TokenMismatchException` → 419
- `HttpException` → Uses exception's status code

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

[](#configuration)

Publish the config to customize response keys:

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

Modify `config/response.php`:

```
return [
    'status_key'  => 'status',
    'message_key' => 'message',
    'data_key'    => 'data',
];
```

Testing
-------

[](#testing)

The package includes a trait to make testing API responses easier:

```
use Hiteshpadhara\ResponseMacro\Tests\AssertsApiResponses;
use Tests\TestCase;

class UserApiTest extends TestCase
{
    use AssertsApiResponses;

    /** @test */
    public function it_returns_user_list()
    {
        $response = $this->getJson('/api/users');

        $this->assertApiSuccess($response);
        $this->assertApiHasData($response);
    }

    /** @test */
    public function it_returns_validation_errors()
    {
        $response = $this->postJson('/api/users', []);

        $this->assertApiError($response, 422);
        $this->assertApiHasErrors($response);
    }

    /** @test */
    public function it_returns_paginated_response()
    {
        $response = $this->getJson('/api/users?page=1');

        $this->assertApiHasPagination($response);
    }
}
```

Testing the Package
-------------------

[](#testing-the-package)

Run the package tests:

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

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

[](#requirements)

- PHP 8.1 or higher
- Laravel 10 or 11

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

[](#contributing)

1. Fork the repository.
2. Create your feature branch: `git checkout -b feature/YourFeature`.
3. Commit your changes: `git commit -m 'Add some feature'`.
4. Push to the branch: `git push origin feature/YourFeature`.
5. Submit a pull request.

License
-------

[](#license)

This package is open-sourced software licensed under the [MIT license](LICENSE).

###  Health Score

19

—

LowBetter than 10% of packages

Maintenance57

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity11

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.

### Community

Maintainers

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

---

Top Contributors

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

### Embed Badge

![Health badge](/badges/hiteshpadhara-laravel-response-macro/health.svg)

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

###  Alternatives

[stripe/stripe-php

Stripe PHP Library

4.0k143.3M480](/packages/stripe-stripe-php)[twilio/sdk

A PHP wrapper for Twilio's API

1.6k92.9M272](/packages/twilio-sdk)[knplabs/github-api

GitHub API v3 client

2.2k15.8M187](/packages/knplabs-github-api)[facebook/php-business-sdk

PHP SDK for Facebook Business

90121.9M34](/packages/facebook-php-business-sdk)[meilisearch/meilisearch-php

PHP wrapper for the Meilisearch API

73813.7M114](/packages/meilisearch-meilisearch-php)[google/gax

Google API Core for PHP

263103.1M454](/packages/google-gax)

PHPackages © 2026

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