PHPackages                             philiprehberger/laravel-response-macros - 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. philiprehberger/laravel-response-macros

ActiveLibrary[API Development](/categories/api)

philiprehberger/laravel-response-macros
=======================================

Response macros for consistent, standardized API responses in Laravel

v1.1.3(1mo ago)15[1 PRs](https://github.com/philiprehberger/laravel-response-macros/pulls)MITPHPPHP ^8.2CI passing

Since Mar 9Pushed 1mo agoCompare

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

READMEChangelogDependencies (9)Versions (6)Used By (0)

Laravel Response Macros
=======================

[](#laravel-response-macros)

[![Tests](https://github.com/philiprehberger/laravel-response-macros/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/laravel-response-macros/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/b5bba153fa16b5c94e5efe9ad4cefc020252dbab03b7a84343e438856a1b8d84/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f6c61726176656c2d726573706f6e73652d6d6163726f732e737667)](https://packagist.org/packages/philiprehberger/laravel-response-macros)[![License](https://camo.githubusercontent.com/da31cfbd4ddb0059e5a6837daa9c976009b12199d4ef00e7741f4f6144b91d22/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f7068696c69707265686265726765722f6c61726176656c2d726573706f6e73652d6d6163726f73)](LICENSE)

Response macros for consistent, standardized API responses in Laravel.

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

[](#requirements)

- PHP 8.2+
- Laravel 11 or 12

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

[](#installation)

```
composer require philiprehberger/laravel-response-macros
```

The service provider is auto-discovered by Laravel. No manual registration is needed.

### Publish the config (optional)

[](#publish-the-config-optional)

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

This copies `config/response-macros.php` to your application's config directory.

Usage
-----

[](#usage)

### Configuration

[](#configuration)

```
// config/response-macros.php

return [
    // Key used to wrap data in the envelope() macro
    'envelope_key' => 'data',

    // Key used to nest metadata in the envelope() macro
    'meta_key' => 'meta',

    // When true, each response body includes a "status" key mirroring the HTTP status code
    'include_status_code' => true,
];
```

### `response()->success()`

[](#response-success)

Returns a `200 OK` response (or any 2xx) indicating a successful operation.

**Signature**

```
response()->success(mixed $data = null, string $message = 'Success', int $status = 200): JsonResponse
```

> **Note:** The `$status` parameter must be a 2xx status code (200–299). Passing a non-2xx status throws `InvalidArgumentException`.

**Example**

```
return response()->success($user, 'User retrieved successfully');
```

**Response**

```
{
    "success": true,
    "message": "User retrieved successfully",
    "data": { "id": 1, "name": "Jane Doe" },
    "status": 200
}
```

### `response()->error()`

[](#response-error)

Returns a `400 Bad Request` response (or any 4xx/5xx) indicating a failed operation.

**Signature**

```
response()->error(string $message = 'Error', int $status = 400, mixed $errors = null): JsonResponse
```

> **Note:** The `$status` parameter must be a 4xx or 5xx status code (400–599). Passing a non-error status throws `InvalidArgumentException`.

**Example**

```
return response()->error('Resource not found', 404);
```

**Response**

```
{
    "success": false,
    "message": "Resource not found",
    "errors": null,
    "status": 404
}
```

With additional error detail:

```
return response()->error('Payment failed', 402, ['code' => 'card_declined']);
```

```
{
    "success": false,
    "message": "Payment failed",
    "errors": { "code": "card_declined" },
    "status": 402
}
```

### `response()->paginated()`

[](#response-paginated)

Wraps a `LengthAwarePaginator` with standardized pagination metadata.

**Signature**

```
response()->paginated(LengthAwarePaginator $paginator, string $message = 'Success'): JsonResponse
```

**Example**

```
$users = User::paginate(15);

return response()->paginated($users, 'Users retrieved');
```

**Response**

```
{
    "success": true,
    "message": "Users retrieved",
    "data": [ ... ],
    "meta": {
        "current_page": 1,
        "last_page": 4,
        "per_page": 15,
        "total": 60
    },
    "status": 200
}
```

### `response()->validationError()`

[](#response-validationerror)

Returns a `422 Unprocessable Entity` response from a `Validator` instance or a `MessageBag`.

**Signature**

```
response()->validationError(Validator|MessageBag $validator, string $message = 'The given data was invalid.'): JsonResponse
```

**Example with a Validator**

```
$validator = Validator::make($request->all(), [
    'email' => 'required|email',
    'name'  => 'required|string|max:255',
]);

if ($validator->fails()) {
    return response()->validationError($validator);
}
```

**Example with a MessageBag**

```
$messages = new \Illuminate\Support\MessageBag([
    'email' => ['This email address is already taken.'],
]);

return response()->validationError($messages);
```

**Response**

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

You can customize the error message:

```
return response()->validationError($validator, 'Please fix the highlighted fields.');
```

### `response()->noContent()`

[](#response-nocontent)

> **Removed in v1.1.0.** The `noContent()` macro was dead code — Laravel's `ResponseFactory` defines `noContent()` natively, and native methods take precedence over macros. Use Laravel's built-in `response()->noContent()` instead, which returns an HTTP `204` with an empty body.

### `response()->accepted()`

[](#response-accepted)

Returns a `202 Accepted` response indicating the request has been queued or is being processed asynchronously.

**Signature**

```
response()->accepted(mixed $data = null, string $message = 'Accepted'): JsonResponse
```

**Example**

```
ProcessReportJob::dispatch($report);

return response()->accepted(['job_id' => $job->id], 'Report generation queued');
```

**Response**

```
{
    "success": true,
    "message": "Report generation queued",
    "data": { "job_id": "abc-123" },
    "status": 202
}
```

### `response()->envelope()`

[](#response-envelope)

Wraps arbitrary data under a configurable key with optional metadata. Useful when you need full control over the response shape without the opinionated `success`/`message` fields.

**Signature**

```
response()->envelope(mixed $data, array $meta = []): JsonResponse
```

**Example without metadata**

```
return response()->envelope($product);
```

**Response**

```
{
    "data": { "id": 42, "name": "Widget Pro" },
    "status": 200
}
```

**Example with metadata**

```
return response()->envelope($results, [
    'version' => '2.1',
    'locale'  => 'en-US',
    'cached'  => true,
]);
```

**Response**

```
{
    "data": [ ... ],
    "meta": {
        "version": "2.1",
        "locale": "en-US",
        "cached": true
    },
    "status": 200
}
```

### Omitting the Status Code from the Body

[](#omitting-the-status-code-from-the-body)

Set `include_status_code` to `false` in `config/response-macros.php` to remove the `"status"` key from all response bodies:

```
'include_status_code' => false,
```

Before:

```
{ "success": true, "message": "OK", "data": null, "status": 200 }
```

After:

```
{ "success": true, "message": "OK", "data": null }
```

The HTTP status code on the response itself is never affected by this option.

API
---

[](#api)

MacroSignatureDescription`response()->success()``success(mixed $data, string $message, int $status): JsonResponse`2xx success response`response()->error()``error(string $message, int $status, mixed $errors): JsonResponse`4xx/5xx error response`response()->paginated()``paginated(LengthAwarePaginator $paginator, string $message): JsonResponse`Paginated response with metadata`response()->validationError()``validationError(Validator|MessageBag $validator, string $message): JsonResponse`422 validation error`response()->accepted()``accepted(mixed $data, string $message): JsonResponse`202 async accepted response`response()->envelope()``envelope(mixed $data, array $meta): JsonResponse`Data under configurable keyDevelopment
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

License
-------

[](#license)

MIT

###  Health Score

40

—

FairBetter than 88% of packages

Maintenance89

Actively maintained with recent releases

Popularity7

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity50

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

Every ~2 days

Total

5

Last Release

53d ago

### Community

Maintainers

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

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (13 commits)")

---

Tags

responsejsonapilaravelmacros

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-laravel-response-macros/health.svg)

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

###  Alternatives

[dragon-code/laravel-json-response

Automatically always return a response in JSON format

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

Simple Laravel package to return Json responses.

17324.6k](/packages/obiefy-api-response)[kennedy-osaze/laravel-api-response

Renders consistent HTTP JSON responses for API-based projects

654.5k](/packages/kennedy-osaze-laravel-api-response)[wayofdev/laravel-symfony-serializer

📦 Laravel wrapper around Symfony Serializer.

2113.6k](/packages/wayofdev-laravel-symfony-serializer)[djurovicigoor/larajsonresponse

Laravel API wrapper for returning JSON response.

116.8k](/packages/djurovicigoor-larajsonresponse)

PHPackages © 2026

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