# Laravel API Response documentation (v6.x)

> Canonical: https://pharaonic.dev/packages/laravel/api-response/6.x  
> Version: v6.x (latest release 6.0.0, 2026-11-25)  
> Install: composer require pharaonic/laravel-api-response  
> Requires: PHP 8.0, Laravel 6  
> Repository: https://github.com/Pharaonic/laravel-api-response  
> All versions: https://pharaonic.dev/packages/laravel/api-response/6.x.md

:::badges
- Laravel Package {color=blue}
- v6.0.0 {color=green}
- MIT License {color=purple}
:::

# Laravel API Response

API Response gives your Laravel API one predictable response shape. You return a `Response` builder from a controller, chain what the response needs in any order, and Laravel turns it into a JSON response when it sends it. Data, API resources and paginators are resolved for you, errors carry stable application codes, and optional parts such as notifications, request IDs and SEO tags appear only when you ask for them.

:::features
### One Envelope
success, message, code, data, errors and meta in a fixed order. Fields you never set are left out; values you set, even null or an empty list, are always sent.

### Every Paginator
Length-aware, simple and cursor paginators, and your own through an adapter, become their items plus meta.pagination with only the facts the paginator knows.

### API Resources
JsonResource and resource collections resolve with the current request, keep conditional fields and merge with() and additional() into meta.

### Opt-in Exceptions
An exception renderer you register yourself maps API exceptions to the envelope, keeps their headers, and never reports or touches web pages.

### Profiles
Rename fields, reshape pagination and notifications, or drop the envelope per response, per route or by Accept media type.

### Request IDs
A middleware assigns a validated request ID, sends it in a header and the body, and adds it to every log record of that request.
:::

:::info Nothing is rewritten behind your back
The package shapes only the builders you return. Responses you build with `response()->json()`, views and redirects are untouched, and exception rendering stays off until you register it.
:::

## Installation

Install the package with Composer. The service provider is registered automatically, and the package needs no database or migrations.

### Requirements

- PHP 8.0
- Laravel 6.x (6.20 or later)

### Composer Installation

```bash title="Terminal" no-line-numbers
composer require pharaonic/laravel-api-response
```

### Publish Configuration

Publishing is optional; the defaults work as they are. Publish the file to `config/pharaonic/api-response.php` when you want to change them:

```bash title="Terminal" no-line-numbers
php artisan vendor:publish --tag=api-response-config
```

### Publish Translations

The package's messages ship in English and Arabic and follow the application locale. Publish them to `resources/lang/vendor/api-response` to change a line or add a language:

```bash title="Terminal" no-line-numbers
php artisan vendor:publish --tag=api-response-translations
```

### Optional: SEO Tags

To send SEO tags with `withSEO()`, also install `pharaonic/laravel-seo` 6.1 or later:

```bash title="Terminal" no-line-numbers
composer require pharaonic/laravel-seo
```

:::success Installation Complete
You're all set! Return `Response::success()` from any controller.
:::

## Configuration

Every option lives in `config/pharaonic/api-response.php` and is read under `pharaonic.api-response`. Options are checked when a response is built, and a wrong value throws an `InvalidArgumentException` that names the key.

### Options

| Key | Default | Description |
| --- | --- | --- |
| `default_profile` | `'default'` | The profile a response uses when nothing else chooses one. |
| `profiles` | `['default' => Profile::class]` | Profile names and their classes, each extending `Pharaonic\Laravel\ApiResponse\Profiles\Profile`. |
| `json_options` | `JSON_UNESCAPED_UNICODE \| JSON_UNESCAPED_SLASHES` | Flags for `json_encode()`. `JSON_THROW_ON_ERROR` is always added and `JSON_PARTIAL_OUTPUT_ON_ERROR` is refused. |
| `envelope.fields` | each field under its own name | The name each envelope field is sent under: `success`, `message`, `code`, `data`, `errors`, `meta`, `notifications`, `seo`, `request_id`. Names must be unique. |
| `pagination.enabled` | `true` | Send paginators as their items plus `meta.pagination`. |
| `pagination.query_string.enabled` | `true` | Keep the request's query string in pagination links by default. |
| `pagination.query_string.except` | `['token', 'api_key', 'access_token', 'password']` | Keys never copied into pagination links, compared without case. |
| `pagination.adapters` | `[]` | Your own `Contracts\PaginationAdapter` classes, asked before the built-in ones. |
| `notifications.default_type` | `'info'` | The type of a notification that names none. Must be one of `types`. |
| `notifications.types` | `['success', 'error', 'warning', 'info']` | The notification types a response may use. |
| `seo.missing_driver` | `'throw'` | What `withSEO()` does without `pharaonic/laravel-seo`: `'throw'` or `'ignore'`. |
| `request_id.header` | `'X-Request-ID'` | The header that carries the request ID, in and out. |
| `request_id.generator` | `'uuid'` | `'uuid'`, or an invokable class that returns the ID. |
| `request_id.trust_incoming` | `false` | Reuse a valid incoming ID instead of generating one. |
| `request_id.max_length` | `128` | The longest incoming or generated ID accepted (1 to 1024). |
| `request_id.include_in_body` | `true` | Add the ID to the body unless the response or profile says otherwise. |
| `request_id.logging` | `true` | Add the ID to log records as `extra.request_id`. |
| `exceptions.paths` | `['api/*']` | Request paths rendered as JSON even when the request does not ask for JSON. |
| `exceptions.mappers` | `[]` | Exception class or interface => `Contracts\ExceptionMapper` class. |
| `content_negotiation.enabled` | `false` | Choose the profile from the `Accept` header. |
| `content_negotiation.media_types` | `[]` | Media type => profile name, e.g. `'application/vnd.acme.mobile+json' => 'mobile'`. |

### Renaming Envelope Fields

Rename a field for every response by changing its name:

```php title="config/pharaonic/api-response.php"
'envelope' => [
    'fields' => [
        'success' => 'ok',
        'message' => 'message',
        'code' => 'code',
        'data' => 'result',
        'errors' => 'errors',
        'meta' => 'meta',
        'notifications' => 'notifications',
        'seo' => 'seo',
        'request_id' => 'request_id',
    ],
],
```

:::warning Every field needs a unique name
Two fields under the same name, a missing field, or an unknown one throws an `InvalidArgumentException` when a response is built, instead of silently overwriting data.
:::

## Basic Usage

Start a response with a static constructor, chain what it needs, and return it. `Response` implements Laravel's `Responsable`, so Laravel builds the HTTP response when it sends it.

```php title="app/Http/Controllers/PostController.php"
use App\Post;
use Pharaonic\Laravel\ApiResponse\Response;

class PostController extends Controller
{
    public function show(Post $post)
    {
        return Response::success($post)
            ->message('Post retrieved successfully.')
            ->meta('version', '1.0');
    }
}
```

```json title="Response" no-copy
{
  "success": true,
  "message": "Post retrieved successfully.",
  "data": {"id": 1, "title": "Laravel SEO"},
  "meta": {"version": "1.0"}
}
```

:::info Laravel's Response facade
Laravel aliases its own `Response` facade globally. Importing `Pharaonic\Laravel\ApiResponse\Response` in a file takes precedence there. In a file that also needs Laravel's facade, give one of them another name: `use Pharaonic\Laravel\ApiResponse\Response as ApiResponse;`.
:::

### Errors

An error needs a message and a status of 400 or more. `code()` sets a stable, machine-readable application code, separate from the HTTP status and the message you show:

```php title="app/Http/Controllers/PaymentController.php"
return Response::error('Insufficient balance.', 422)->code('INSUFFICIENT_BALANCE');
```

```json title="Response" no-copy
{
  "success": false,
  "message": "Insufficient balance.",
  "code": "INSUFFICIENT_BALANCE"
}
```

### The Envelope

Fields are always sent in this order, and only when they are set:

| Field | Sent when |
| --- | --- |
| `success` | always: `true` below 400, `false` from 400 |
| `message` | `message()` was called, or the response is an error |
| `code` | `code()` was called, or a helper set one |
| `data` | the constructor received data, or `data()` was called |
| `errors` | `errors()` was called |
| `meta` | there is metadata from `meta()`, a resource, or pagination |
| `notifications` | `notify()` was called |
| `seo` | `withSEO()` was called |
| `request_id` | the request has an ID and the response includes it |

### Unset Is Not Empty

A field you never set is left out. A value you set is always sent, even `null`, `[]`, `false`, `0` or `''`:

```php
Response::success();         // {"success":true}
Response::success(null);     // {"success":true,"data":null}
Response::success([]);       // {"success":true,"data":[]}
```

### Data Types

`data` accepts arrays, scalars, Eloquent models and collections, `Arrayable`, `JsonSerializable` and `Jsonable` objects, API resources and paginators. Models keep their `$hidden` and `$casts` rules, and resources are never wrapped twice, so there is no `data.data`.

### Order Does Not Matter

Every fluent method only records state, and the response is built at the end, so these two give the same response:

```php
Response::success($post)->message('Saved.')->notify('Saved.', 'success');
Response::success()->notify('Saved.', 'success')->data($post)->message('Saved.');
```

Setters such as `data()`, `message()`, `code()`, `status()` and `profile()` keep the last value. `meta()`, `notify()`, `header()` and `transform()` add to what is already there. Building the same builder twice gives the same response, without duplicating notifications, SEO tags or metadata.

### Building the Response Yourself

Call `response()` to get the HTTP response for the current request, for example inside middleware or a test:

```php
$response = Response::success(['ok' => true])->response();

$response->getStatusCode(); // 200
```

## Status Helpers & Error Codes

Each constructor sets the status, and the error helpers also set a message and a code. The default messages are translated in the application locale; a message you pass is sent as it is. Codes never change with the locale.

### Success Helpers

| Constructor | Status | Body |
| --- | --- | --- |
| `Response::success($data = null)` | 200 | the envelope |
| `Response::created($data = null)` | 201 | the envelope |
| `Response::accepted($data = null)` | 202 | the envelope |
| `Response::noContent()` | 204 | none |

Called without an argument, `success()`, `created()` and `accepted()` send no `data` field.

### Error Helpers

| Constructor | Status | Default message | Code |
| --- | --- | --- | --- |
| `Response::error($message, $status = 400)` | 400 or the given status | your message | none |
| `Response::unauthorized($message = null)` | 401 | Unauthenticated. | `UNAUTHENTICATED` |
| `Response::forbidden($message = null)` | 403 | This action is unauthorized. | `FORBIDDEN` |
| `Response::notFound($message = null)` | 404 | Not Found. | `NOT_FOUND` |
| `Response::validationError($errors, $message = null)` | 422 | The given data was invalid. | `VALIDATION_ERROR` |

```php title="app/Http/Controllers/RegisterController.php"
return Response::validationError(['email' => ['The email field is required.']]);
```

```json title="Response" no-copy
{
  "success": false,
  "message": "The given data was invalid.",
  "code": "VALIDATION_ERROR",
  "errors": {"email": ["The email field is required."]}
}
```

### What Each Response Carries

A success carries `data`; an error carries `errors`. Calling `data()` on an error or `errors()` on a success throws an `InvalidArgumentException`, so `success` never contradicts the body. Put the details of an error in `errors()` or `meta()`. `message`, `code`, `meta`, notifications, request IDs and SEO tags work on both.

```php
Response::error('Payment failed.', 402)->meta('retry_after', 30);   // fine
Response::error('Payment failed.', 402)->data($order);              // InvalidArgumentException
Response::success($order)->errors(['card' => ['Declined.']]);       // InvalidArgumentException
```

### Translated Messages

The default messages come from `api-response::messages` (`unauthenticated`, `forbidden`, `not_found`, `validation`), so with the locale set to `ar` `Response::notFound()` sends `"message": "غير موجود."`. A locale without the line falls back to English. See [Exception Rendering](#exceptions) for the full list of keys and how to publish them.

### Changing the Status

`status()` sets any status from 200 to 599, but it keeps the response honest: a success keeps a status below 400 and an error one of 400 or more. Anything else throws an `InvalidArgumentException`.

```php
Response::error('Conflict.')->status(409);     // 409, "success": false
Response::success($post)->status(203);         // 203, "success": true
Response::success()->status(422);              // InvalidArgumentException: use Response::error()
```

A redirect status (3xx) counts as a success. Set the `Location` header yourself with `header()`.

### Error Codes

An error code is a stable identifier your clients can switch on. It is not the HTTP status and not the message you translate. `code()` accepts letters, digits, `_`, `.`, `:` and `-`, and `code(null)` removes it:

```php
Response::error(__('payments.balance'), 422)->code('INSUFFICIENT_BALANCE');
```

### Responses Without a Body

`204` and `304` responses send only their headers: no envelope, notifications or metadata. A `HEAD` request gets the headers of the response, `Content-Type` included, with an empty body.

```php
return Response::noContent()->header('X-Deleted', '1');
```

## Pagination

Pass a paginator as the data and the response sends its items in `data` and its facts in `meta.pagination`. Each type sends only what it really knows: a simple paginator never gets a total, and a cursor paginator never gets a page number or item positions.

### The Shape

`meta.pagination` always has the same groups, in this order:

| Key | Length-aware | Simple | Cursor | Holds |
| --- | --- | --- | --- | --- |
| `type` | `length_aware` | `simple` | `cursor` | The kind of paginator. |
| `pages` | yes | yes | yes | `current`, `last`, `per_page` and `has_more`, as far as the paginator knows them. |
| `items` | yes | yes | no | `total`, `from` and `to`: the positions of the page's items. |
| `cursors` | no | no | yes | The `current`, `prev` and `next` cursor tokens. |
| `links` | yes | yes | yes | The page URLs, after the [query-string policy](#query-strings). |

### Length-Aware Paginators

`paginate()`, and a `LengthAwarePaginator` you build yourself:

```php title="app/Http/Controllers/PostController.php"
return Response::success(Post::query()->paginate(15));
```

```json title="Response" no-copy
{
  "success": true,
  "data": [{"id": 1, "title": "First post"}],
  "meta": {
    "pagination": {
      "type": "length_aware",
      "pages": {
        "current": 1,
        "last": 10,
        "per_page": 15,
        "has_more": true
      },
      "items": {
        "total": 150,
        "from": 1,
        "to": 15
      },
      "links": {
        "first": "https://example.com/api/posts?page=1",
        "last": "https://example.com/api/posts?page=10",
        "prev": null,
        "next": "https://example.com/api/posts?page=2"
      }
    }
  }
}
```

On an empty result, `items.from` and `items.to` are `null`, `items.total` is `0` and `pages.last` is `1`.

### Simple Paginators

`simplePaginate()`, and a `Paginator` you build yourself. There is no `pages.last`, no `items.total` and no first or last link:

```json title="meta.pagination" no-copy
{
  "type": "simple",
  "pages": {
    "current": 2,
    "per_page": 15,
    "has_more": true
  },
  "items": {
    "from": 16,
    "to": 30
  },
  "links": {
    "prev": "https://example.com/api/posts?page=1",
    "next": "https://example.com/api/posts?page=3"
  }
}
```

### Cursor Paginators

`cursorPaginate()` exists from Laravel 8.41, so cursor paginators are supported on the 8.x line and later. They have no page numbers and no item positions, so `pages` holds only `per_page` and `has_more`, `items` is left out, and `cursors` holds the encoded tokens; `cursors.current` is `null` on the first page:

```json title="meta.pagination" no-copy
{
  "type": "cursor",
  "pages": {
    "per_page": 15,
    "has_more": true
  },
  "cursors": {
    "current": null,
    "prev": null,
    "next": "eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0"
  },
  "links": {
    "prev": null,
    "next": "https://example.com/api/posts?cursor=eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0"
  }
}
```

### Custom Page Names

A paginator's own page name is kept in its links, with every query-string policy:

```php
return Response::success(Post::query()->paginate(15, ['*'], 'p'));
// "next": "https://example.com/api/posts?p=2"
```

### Other Paginators

For anything else, such as a page of results from an external API, write a `Contracts\PaginationAdapter` and register it. Send only what your paginator knows, in the same groups (`type`, `pages`, `items` or `cursors`, `links`), so clients read every paginator the same way. Registered adapters are asked before the built-in ones. Pass each URL you send through `$url`, with its page or cursor parameter name, so the response's query-string policy applies to it:

```php title="app/Pagination/RemotePageAdapter.php"
use App\Remote\RemotePage;
use Closure;
use Pharaonic\Laravel\ApiResponse\Contracts\PaginationAdapter;

class RemotePageAdapter implements PaginationAdapter
{
    public function supports(object $paginator): bool
    {
        return $paginator instanceof RemotePage;
    }

    public function items(object $paginator): mixed
    {
        return $paginator->items;
    }

    public function meta(object $paginator, Closure $url): array
    {
        return [
            'type' => 'token',
            'pages' => ['has_more' => $paginator->nextToken !== null],
            'links' => [
                'next' => $paginator->nextToken === null
                    ? null
                    : $url($paginator->path.'?page_token='.$paginator->nextToken, 'page_token'),
            ],
        ];
    }
}
```

```php title="config/pharaonic/api-response.php"
'pagination' => [
    // ...
    'adapters' => [App\Pagination\RemotePageAdapter::class],
],
```

### Turning Pagination Off

`withoutPagination()` sends the items alone, without `meta.pagination`. Set `pagination.enabled` to `false`, or override `paginates()` in a profile, to do it for every response:

```php
return Response::success(Post::query()->paginate(15))->withoutPagination();
```

### Pagination and Metadata

`meta.pagination` belongs to the package: `meta('pagination', ...)` throws an `InvalidArgumentException`. Your other metadata sits next to it.

:::info The paginator is never changed
Links are rewritten when the response is built, from copies. The paginator, its appended query and the request stay as they were.
:::

## Query Strings

Pagination links can keep the request's query string, so a client following `next` keeps its search and sort. The page or cursor parameter is always kept, and denied keys never are.

### The Three Policies

```php
// Every key except the denied ones (the default).
->withQueryString()

// Only these keys, still without the denied ones.
->withQueryString(['search', 'sort'])

// No extra keys; the page or cursor parameter stays.
->withoutQueryString()
```

For a request to `/api/posts?search=café&sort=-id&token=secret&page=2`:

| Policy | `next` link |
| --- | --- |
| default | `/api/posts?search=caf%C3%A9&sort=-id&page=3` |
| `withQueryString(['search'])` | `/api/posts?search=caf%C3%A9&page=3` |
| `withoutQueryString()` | `/api/posts?page=3` |

`token` is left out in every case, because it is in `pagination.query_string.except`.

### The Default

`pagination.query_string.enabled` chooses what a response does when it calls neither method. Set it to `false` to keep only the page parameter unless a response calls `withQueryString()`.

### Denied Keys

`pagination.query_string.except` lists keys that are never copied into a link, compared without case, even when an allowlist names them. Add every key that can carry a credential:

```php title="config/pharaonic/api-response.php"
'query_string' => [
    'enabled' => true,
    'except' => ['token', 'api_key', 'access_token', 'password', 'signature'],
],
```

:::warning Links echo what the client sent
A preserved query string repeats the client's own values in the response. Keep credentials and signed values in `except`, or use an allowlist on public endpoints.
:::

### What Is Rewritten

Only the pagination links the package builds are rewritten. Keys the paginator appended itself (`appends()`) follow the same policy and win over request keys with the same name. Nested keys (`filter[status]`), non-ASCII values and cursor tokens are encoded with RFC 3986. URLs inside your own data are never touched.

## API Resources

Laravel's `JsonResource` and resource collections are resolved with the current request through their own `resolve()`, so `when()`, `whenLoaded()`, `mergeWhen()`, nested resources and `$collects` keep working. Their output goes into `data` without Laravel's `data` wrapper.

### A Single Resource

```php title="app/Http/Controllers/PostController.php"
use App\Http\Resources\PostResource;

return Response::success(new PostResource($post));
```

### Collections and Paginated Collections

A collection of an unpaginated query sends a list. A collection of a paginator sends the transformed items and the normalized `meta.pagination`, for anonymous and custom collections alike:

```php
return Response::success(PostResource::collection(Post::query()->paginate(15)));
return Response::success(new PostCollection(Post::query()->simplePaginate(15)));
```

An empty collection is sent as `"data": []`.

### Resource Metadata

A resource's `with()` and `additional()` become metadata. The contents of their `meta` key are merged into `meta`; every other key, such as `links`, keeps its own name inside `meta`:

```php title="app/Http/Resources/PostResource.php"
public function with($request)
{
    return [
        'meta' => ['resource' => 'post'],
        'links' => ['self' => url('/api/posts/'.$this->id)],
    ];
}
```

```json title="Response" no-copy
{
  "success": true,
  "data": {"id": 1, "title": "Laravel SEO"},
  "meta": {
    "links": {"self": "https://example.com/api/posts/1"},
    "resource": "post"
  }
}
```

### Collision Rules

Metadata merges in a fixed order, and a later key replaces an earlier one:

1. the resource's `with()`, then its `additional()`;
2. the response's `meta()`;
3. `meta.pagination`, which only the package sets.

### Custom Pagination Information

When a resource collection defines `paginationInformation($request, $paginated, $default)`, it is called with Laravel's paginator array as `$paginated` and `['pagination' => ...]`, the normalized pagination, as `$default`. The `pagination` key it returns becomes `meta.pagination` (leave it out to send none), and its other keys are merged into `meta`:

```php title="app/Http/Resources/PostCollection.php"
public function paginationInformation($request, $paginated, $default)
{
    $default['pagination']['label'] = 'posts';

    return $default;
}
```

### Status and withResponse()

The resource's `withResponse()` runs on the final response, so headers it sets are kept. The status always comes from the builder: Laravel's automatic `201` for a model created in this request is not applied, so return `Response::created(...)` instead.

## Notifications

`notify()` adds a message for the client to display, such as a toast. Notifications are part of the response body only; nothing is sent through Laravel's notification system.

```php title="app/Http/Controllers/PostController.php"
return Response::created(new PostResource($post))
    ->notify('Post created.', 'success')
    ->notify('Waiting for review.');
```

```json title="Response" no-copy
{
  "success": true,
  "data": {"id": 1, "title": "Laravel SEO"},
  "notifications": [
    {"type": "success", "message": "Post created."},
    {"type": "info", "message": "Waiting for review."}
  ]
}
```

### Structured Fields

Each notification has a `type` and a `message`, and optionally a `title`, a `duration` in milliseconds and `data`. Named arguments read best:

```php
return Response::success(new PostResource($post))->notify(
    message: 'Post created successfully.',
    type: 'success',
    title: 'Done',
    duration: 5000,
    data: ['post_id' => $post->id],
);
```

Optional fields that are not set are left out. Notifications keep the order they were added in, and an error response can carry them too.

### Types

A notification without a type uses `notifications.default_type` (`info`). The type must be one of `notifications.types`, so add your own there:

```php title="config/pharaonic/api-response.php"
'notifications' => [
    'default_type' => 'info',
    'types' => ['success', 'error', 'warning', 'info', 'celebrate'],
],
```

An unknown type throws an `InvalidArgumentException` when the response is built, and a negative duration throws when `notify()` is called.

### Custom Shape

Override `notification()` in a [profile](#profiles) to send notifications in another shape:

```php title="app/Http/Profiles/MobileProfile.php"
public function notification(array $notification): array
{
    return ['text' => $notification['message'], 'kind' => $notification['type']];
}
```

:::info Bodyless responses
A `204` or `304` response, or the response to a `HEAD` request, has no body, so its notifications are not sent.
:::

## Profiles & Negotiation

A profile decides how a response is shaped: field names, the body, pagination and notification shapes, default headers, and whether the body carries the request ID. The `default` profile follows the configuration. Write your own when one client, such as a mobile app, needs another shape.

### Writing a Profile

Extend `Profiles\Profile` and override only what differs. Profiles are built by the container for each response, so their constructor may type-hint dependencies:

```php title="app/Http/Profiles/MobileProfile.php"
namespace App\Http\Profiles;

use Pharaonic\Laravel\ApiResponse\Profiles\Profile;

class MobileProfile extends Profile
{
    public function fields(): array
    {
        return array_merge(parent::fields(), ['success' => 'ok', 'data' => 'result']);
    }

    public function pagination(array $pagination): array
    {
        return array_intersect_key($pagination, array_flip(['type', 'pages', 'cursors']));
    }

    public function headers(): array
    {
        return ['X-Profile' => 'mobile'];
    }

    public function includesRequestId(): bool
    {
        return false;
    }
}
```

Register it under a name:

```php title="config/pharaonic/api-response.php"
'profiles' => [
    'default' => Pharaonic\Laravel\ApiResponse\Profiles\Profile::class,
    'mobile' => App\Http\Profiles\MobileProfile::class,
],
```

### What a Profile Controls

| Method | Default | Purpose |
| --- | --- | --- |
| `fields(): array` | `envelope.fields` | The name of each field. Return every field: merge your changes into `parent::fields()`. |
| `body(array $parts): mixed` | the envelope with `fields()` names | Builds the body from the parts that are set, keyed by canonical name. |
| `pagination(array $pagination): array` | unchanged | Shapes `meta.pagination`. |
| `notification(array $notification): array` | drops unset optional fields | Shapes each notification. |
| `headers(): array` | `[]` | Headers for every response of the profile; a response's own headers win. |
| `includesRequestId(): bool` | `request_id.include_in_body` | Whether the body carries the request ID when the response does not say. |
| `paginates(): bool` | `pagination.enabled` | Whether paginators send `meta.pagination`. |

### Sending Data Without an Envelope

Override `body()` to send another shape, such as the data alone:

```php title="app/Http/Profiles/RawProfile.php"
class RawProfile extends Profile
{
    public function body(array $parts): mixed
    {
        return $parts['data'] ?? null;
    }
}
```

### Choosing the Profile

The first of these that applies wins:

1. `->profile('mobile')` on the response;
2. the `UseResponseProfile` middleware on the route;
3. the negotiated `Accept` media type, when content negotiation is on;
4. `default_profile`.

An unknown name in `profile()` or the middleware throws an `InvalidArgumentException`; it never falls back silently.

```php title="routes/api.php"
use Pharaonic\Laravel\ApiResponse\Http\Middleware\UseResponseProfile;

Route::middleware(UseResponseProfile::class.':mobile')->group(function () {
    Route::get('feed', 'FeedController@index');
});
```

To write `profile:mobile` instead, register the class under that key in `$routeMiddleware` of `app/Http/Kernel.php`.

### Content Negotiation

Map media types to profiles and turn negotiation on. The `Accept` header is parsed with its quality values; the best registered media type with a quality above 0 wins, and anything else falls back to the default profile:

```php title="config/pharaonic/api-response.php"
'content_negotiation' => [
    'enabled' => true,
    'media_types' => [
        'application/vnd.acme.mobile+json' => 'mobile',
    ],
],
```

```bash title="Terminal" no-line-numbers
curl -H "Accept: application/vnd.acme.mobile+json" https://example.com/api/feed
```

A negotiated response is sent with the matched media type as its `Content-Type`, and while negotiation is on, every response carries `Vary: Accept`, added to any `Vary` the response, its profile or a resource sets. Profile names are never read from `Accept`: `Accept: mobile` chooses nothing.

## Headers, Macros & Transforms

### Headers

`header()` adds one header and `withHeaders()` several. A later value replaces an earlier one, and a response's headers win over its profile's:

```php
return Response::success($posts)
    ->header('X-API-Version', '1')
    ->withHeaders(['Cache-Control' => 'private, max-age=60']);
```

Header names must be valid tokens, and values may not contain line breaks or other control characters, so a header can never be split. Anything else throws an `InvalidArgumentException`.

### Conditional Changes

`when()` and `unless()` change the builder when a condition holds, with an optional default for the other case. A closure as the condition receives the builder, and the callback receives the builder and the condition's value:

```php
return Response::success($post)
    ->when($request->user()->isAdmin(), fn (Response $response) => $response->meta('audit', $post->audits))
    ->unless($post->published, fn (Response $response) => $response->notify('This post is a draft.', 'warning'));
```

Both always return the builder, whatever the callback returns.

### Transforming the Payload

`transform()` changes `data` after resources and paginators are resolved and before the envelope is built. Transforms run in the order they were added and never see the envelope or the metadata:

```php
return Response::success(Post::query()->paginate(15))
    ->transform(fn (array $posts) => array_map(fn ($post) => $post + ['type' => 'post'], $posts));
```

### Macros

Register a macro in a service provider's `boot()` method. Inside the closure, `$this` is the builder:

```php title="app/Providers/AppServiceProvider.php"
use Pharaonic\Laravel\ApiResponse\Response;

public function boot()
{
    Response::macro('version', function (string $version) {
        return $this->header('X-API-Version', $version)->meta('version', $version);
    });
}
```

```php
return Response::success($posts)->version('2');
```

A macro cannot use the name of a method the builder already has; that throws an `InvalidArgumentException`. In tests, `Response::flushMacros()` forgets every macro, and `Response::hasMacro('version')` tells whether one is registered.

### JSON Encoding

`json_options` holds the flags passed to `json_encode()`; Unicode and slashes are sent unescaped by default. `JSON_THROW_ON_ERROR` is always added, so invalid UTF-8, `NAN`, resources and recursive values throw a `JsonException` instead of sending an incomplete or false success. `JSON_PARTIAL_OUTPUT_ON_ERROR` is refused.

```php title="config/pharaonic/api-response.php"
'json_options' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRESERVE_ZERO_FRACTION,
```

## Exception Rendering

`ExceptionRenderer` renders the exceptions of API requests in the envelope. It is off until you register it with your exception handler, and it only renders: Laravel still reports every exception as before, once, following your `$dontReport` list.

### Registering the Renderer

On Laravel 6, call it from `render()` in your application's handler, and let Laravel render anything it returns `null` for:

```php title="app/Exceptions/Handler.php"
use Exception;
use Pharaonic\Laravel\ApiResponse\ExceptionRenderer;

public function render($request, Exception $exception)
{
    return (new ExceptionRenderer)($exception, $request) ?? parent::render($request, $exception);
}
```

### Which Requests It Renders

A request is rendered when it expects JSON (`Accept: application/json`, or an AJAX request) or its path matches `exceptions.paths` (`api/*` by default). Web pages are left to Laravel. Unless a [mapper](#exceptions) is configured for it, the renderer also returns `null`, leaving the exception to Laravel, for exceptions that carry their own response:

- `HttpResponseException`;
- exceptions that implement `Responsable` or have a `render()` method, except HTTP exceptions with an error code (below);
- a `ValidationException` created with a response.

### Exceptions With an Error Code

An HTTP exception with a public `errorCode()` method sends that code, in upper case like every code of the envelope, in place of the status code, keeping its status, message and headers. An exception with a public `localizedMessage()` method sends that message, so it is translated by the package that owns it. It is rendered in the envelope even when it has a `render()` method, because the envelope carries everything that method sends, and for every request, even one that matches neither JSON nor `exceptions.paths`: such an exception only comes from an API, and its client may not send `Accept: application/json`. The exceptions of `pharaonic/laravel-api-versioning` and `pharaonic/laravel-api-idempotency` work this way, so they get `success`, the request ID and the response profile like every other error:

```json title="Response" no-copy
{
  "success": false,
  "message": "A request with this idempotency key is still being processed.",
  "code": "IDEMPOTENCY_IN_PROGRESS",
  "request_id": "9b1d…"
}
```

Their messages are translated by those packages from their own `api-versioning::messages` and `api-idempotency::messages` lines. Their codes are sent in upper case, so `idempotency_in_progress` becomes `IDEMPOTENCY_IN_PROGRESS`; compare codes without case if a client also reads that package's own response. An `errorCode()` that returns anything but letters, digits, `_`, `.`, `:` and `-` is ignored and the status code is sent.

### Built-in Mappings

| Exception | Status | Code | Message |
| --- | --- | --- | --- |
| `ValidationException` | its status (422) | `VALIDATION_ERROR` | its message, with `errors` from its bag |
| `AuthenticationException` | 401 | `UNAUTHENTICATED` | its message, or Unauthenticated. |
| `AuthorizationException` | 403 | `FORBIDDEN` | its message, or This action is unauthorized. |
| `ModelNotFoundException` | 404 | `NOT_FOUND` | Not Found. (the model name is sent only in debug mode) |
| `TokenMismatchException` | 419 | `PAGE_EXPIRED` | CSRF token mismatch. |
| any HTTP exception (404 route, 405, 429, `abort()`...) | its status | a fixed code per status from RFC 9110, e.g. `TOO_MANY_REQUESTS`, `CONTENT_TOO_LARGE`; 401 is `UNAUTHENTICATED`, 500 is `SERVER_ERROR`, an unlisted status is `HTTP_<status>` | its message, or the translated status text |
| anything else | 500 | `SERVER_ERROR` | Server Error. |

Codes never follow the framework's status text, so a status sends the same code on every Laravel line.

An HTTP exception keeps its headers, such as `Retry-After` and `X-RateLimit-*` from throttling, `Allow` from a 405, or a `WWW-Authenticate` challenge.

### Translated Messages

Every built-in message is translated in the application locale, from `api-response::messages`. English and Arabic ship with the package; a locale without a line falls back to English. The `code` never changes with the locale, so clients branch on the code and show the message.

| Key | English |
| --- | --- |
| `unauthenticated` | Unauthenticated. |
| `forbidden` | This action is unauthorized. |
| `not_found` | Not Found. |
| `validation` | The given data was invalid. |
| `too_many_attempts` | Too Many Attempts. |
| `page_expired` | CSRF token mismatch. |
| `server_error` | Server Error. |
| `status.<code>` | the status text of an HTTP exception without a message, e.g. `status.503` is Service Unavailable |

Laravel's own English messages (`Unauthenticated.`, `This action is unauthorized.`, `The given data was invalid.`, `Too Many Attempts.`) are translated too. Any other exception message is yours and is sent as it is, so translate it where you throw it: `abort(409, __('orders.exists'))`.

Publish the files to change a line or add a language:

```bash title="Terminal" no-line-numbers
php artisan vendor:publish --tag=api-response-translations
```

```php title="resources/lang/vendor/api-response/fr/messages.php"
return [
    'not_found' => 'Introuvable.',
    // ...
];
```

### Debug Details

With `app.debug` on, an unexpected exception adds `meta.debug` with its class, message, file, line and trace (file, line, class and function of each frame, without arguments). A `ModelNotFoundException` adds the same details plus `model`, the model class, and `ids`, the keys that were not found. With `app.debug` off, nothing about the exception is sent.

:::danger Keep app.debug off in production
`meta.debug` shows file paths and messages that can contain SQL or secrets. It follows `app.debug` only, so it is off whenever Laravel's own debug pages are.
:::

### Your Own Exceptions

Map a domain exception to a response with an `ExceptionMapper`:

```php title="app/Exceptions/InsufficientBalanceMapper.php"
namespace App\Exceptions;

use Illuminate\Http\Request;
use Pharaonic\Laravel\ApiResponse\Response;
use Pharaonic\Laravel\ApiResponse\Contracts\ExceptionMapper;
use Throwable;

class InsufficientBalanceMapper implements ExceptionMapper
{
    public function map(Throwable $exception, Request $request): ?Response
    {
        return Response::error('Insufficient balance.', 422)
            ->code('INSUFFICIENT_BALANCE')
            ->meta('balance', $exception->balance);
    }
}
```

```php title="config/pharaonic/api-response.php"
'exceptions' => [
    'paths' => ['api/*'],
    'mappers' => [
        App\Exceptions\InsufficientBalance::class => App\Exceptions\InsufficientBalanceMapper::class,
    ],
],
```

A mapper may be registered for a class, a parent class or an interface. The mapper of the exception's own class is asked first, then its parents from the closest, then its interfaces, then the built-in mappings. A mapper that returns `null` passes the exception on to the next one. A configured mapper is asked even for an exception that has its own `render()` method, so you can bring a third-party exception into the envelope.

:::tip Exceptions you own can render themselves
An exception class of your own can also return a `Pharaonic\Laravel\ApiResponse\Response` from its `render()` method. Laravel renders it directly and the renderer leaves it alone.
:::

## Request IDs

The `AssignRequestId` middleware gives each request an ID, sends it back in the `X-Request-ID` header, adds it to the response body, and adds it to the log records written during the request.

### Registering the Middleware

Add it to the global middleware, so responses to unknown routes and exceptions get an ID too:

```php title="app/Http/Kernel.php"
protected $middleware = [
    // ...
    \Pharaonic\Laravel\ApiResponse\Http\Middleware\AssignRequestId::class,
];
```

Every response that passes through it gets the header, including responses this package did not build.

### Incoming IDs

An incoming `X-Request-ID` is ignored by default, because clients choose it. Turn on `request_id.trust_incoming` when a proxy you control sets it. A trusted ID is still used only when it is at most `request_id.max_length` characters of letters, digits, `.`, `_`, `:` and `-`; anything else, such as an ID with a line break, is replaced by a new one, so it can never split a header or a log line.

### Generating IDs

IDs are UUIDs by default. To use your own format, set `request_id.generator` to an invokable class; the container builds it, and the ID it returns must pass the same checks, or an `UnexpectedValueException` is thrown:

```php title="app/Support/RequestIdGenerator.php"
namespace App\Support;

use Illuminate\Support\Str;

class RequestIdGenerator
{
    public function __invoke(): string
    {
        return 'req_'.Str::random(24);
    }
}
```

### The ID in the Body

`request_id` is added to the body of every response this package builds while `request_id.include_in_body` is on and the request has an ID. A profile can change that default with `includesRequestId()`, and a response always has the last word:

```php
return Response::success($post)->withoutRequestId();
return Response::success($post)->withRequestId();
```

Without the middleware, the request has no ID and `request_id` is left out, even after `withRequestId()`.

### Log Correlation

While `request_id.logging` is on, a Monolog processor adds the ID to the `extra.request_id` of every record written through the default log channel during the request. The processor reads the ID from the current request each time a record is written, so a long-running worker never writes the ID of an earlier request, and records written outside an HTTP request carry none.

:::info Not distributed tracing
The request ID identifies one request in one application. It is not an OpenTelemetry trace or span ID and is not propagated to outgoing calls.
:::

## SEO Tags

With `pharaonic/laravel-seo` 6.1 or later installed, `withSEO()` adds the current page's SEO tags to the response, for a front end that renders them itself.

```php title="app/Http/Controllers/PostController.php"
seo()->title->set($post->title);
seo()->description->set($post->excerpt);

return Response::success(new PostResource($post))->withSEO();
```

```json title="Response" no-copy
{
  "success": true,
  "data": {"id": 1, "title": "Laravel SEO"},
  "seo": {"title": "Laravel SEO", "description": "Meta tags from code."}
}
```

### Only When Asked

A response never carries `seo` unless that response calls `withSEO()`, whatever the configuration, the profile, or whether the package is installed. The tags are read once, from `seo()->toArray()`, when the response is built, so tags set after `withSEO()` in the same controller are included. The field follows the envelope's `seo` name.

### Without laravel-seo

`withSEO()` without the package (or with a release older than 6.1) throws a `LogicException` that says how to install it. Set `seo.missing_driver` to `ignore` to leave the field out instead:

```php title="config/pharaonic/api-response.php"
'seo' => [
    'missing_driver' => 'ignore',
],
```

## Methods & Classes

All classes are in the `Pharaonic\Laravel\ApiResponse` namespace. Classes under `Support` and the built-in adapters under `Pagination` are internal.

### Constructors

| Method | Description | Returns |
| --- | --- | --- |
| `Response::success(mixed $data = null)` | A 200 success; without an argument, no `data` field. | `Response` |
| `Response::created(mixed $data = null)` | A 201 success. | `Response` |
| `Response::accepted(mixed $data = null)` | A 202 success. | `Response` |
| `Response::noContent()` | A bodyless 204. | `Response` |
| `Response::error(string $message, int $status = 400)` | An error; the status must be 400 to 599. | `Response` |
| `Response::unauthorized(?string $message = null)` | A 401 with code `UNAUTHENTICATED`; without a message, `api-response::messages.unauthenticated`. | `Response` |
| `Response::forbidden(?string $message = null)` | A 403 with code `FORBIDDEN`; without a message, `api-response::messages.forbidden`. | `Response` |
| `Response::notFound(?string $message = null)` | A 404 with code `NOT_FOUND`; without a message, `api-response::messages.not_found`. | `Response` |
| `Response::validationError(array $errors, ?string $message = null)` | A 422 with code `VALIDATION_ERROR` and the errors; without a message, `api-response::messages.validation`. | `Response` |

### Fluent Methods

| Method | Description | Returns |
| --- | --- | --- |
| `data(mixed $data)` | Sets the data, `null` included; refused on an error. | `static` |
| `message(?string $message)` | Sets or removes the message. | `static` |
| `status(int $status)` | Sets the status; a success stays below 400 and an error from 400. | `static` |
| `code(?string $code)` | Sets or removes the application error code. | `static` |
| `errors(?array $errors)` | Sets or removes the errors; refused on a success. | `static` |
| `meta(string\|array $key, mixed $value = null)` | Adds metadata; `pagination` is reserved. | `static` |
| `notify(string $message, ?string $type = null, ?string $title = null, ?int $duration = null, array $data = [])` | Adds a notification. | `static` |
| `profile(string $name)` | Chooses a registered profile. | `static` |
| `withSEO()` | Adds the SEO tags of `pharaonic/laravel-seo`. | `static` |
| `withRequestId()` / `withoutRequestId()` | Adds or leaves out the request ID in the body. | `static` |
| `withQueryString(?array $only = null)` | Keeps every allowed query key, or only the given keys, in pagination links. | `static` |
| `withoutQueryString()` | Keeps only the page or cursor parameter in pagination links. | `static` |
| `withoutPagination()` | Sends a paginator's items without `meta.pagination`. | `static` |
| `header(string $name, string $value)` | Adds a header. | `static` |
| `withHeaders(array $headers)` | Adds several headers. | `static` |
| `when(mixed $value, callable $callback, ?callable $default = null)` | Runs the callback when the value is truthy. | `static` |
| `unless(mixed $value, callable $callback, ?callable $default = null)` | Runs the callback when the value is falsy. | `static` |
| `transform(callable $callback)` | Adds a payload transform. | `static` |
| `response()` | Builds the response for the current request. | `Symfony\Component\HttpFoundation\Response` |
| `toResponse($request)` | Builds the response for the given request (`Responsable`). | `Symfony\Component\HttpFoundation\Response` |

### Macros

| Method | Description | Returns |
| --- | --- | --- |
| `Response::macro(string $name, object\|callable $macro)` | Registers a macro; an existing method name is refused. | `void` |
| `Response::hasMacro(string $name)` | Whether the macro is registered. | `bool` |
| `Response::flushMacros()` | Forgets every macro. | `void` |

### Classes

| Class | Description |
| --- | --- |
| `Profiles\Profile` | Base class of every profile; see [Profiles](#profiles) for its methods. |
| `Contracts\PaginationAdapter` | `supports(object $paginator): bool`, `items(object $paginator): mixed`, `meta(object $paginator, Closure $url): array`. |
| `Contracts\ExceptionMapper` | `map(Throwable $exception, Request $request): ?Response`. |
| `ExceptionRenderer` | Invokable: `(Throwable $exception, Request $request): ?Response`. |
| `Http\Middleware\AssignRequestId` | Assigns, returns and logs the request ID. |
| `Http\Middleware\UseResponseProfile` | Chooses the profile of a route: `UseResponseProfile::class.':name'`. |

### Exceptions Thrown

| Exception | When |
| --- | --- |
| `InvalidArgumentException` | An invalid status, code, header, notification, profile name, macro name or configuration value. |
| `LogicException` | `withSEO()` without `pharaonic/laravel-seo` 6.1 or later, while `seo.missing_driver` is `throw`. |
| `JsonException` | The body cannot be encoded as JSON. |
| `UnexpectedValueException` | A custom request ID generator returned an invalid ID. |

## Use Cases

### 1. A CRUD Controller

One controller with every common response:

```php title="app/Http/Controllers/PostController.php"
namespace App\Http\Controllers;

use App\Http\Requests\StorePost;
use App\Http\Resources\PostResource;
use App\Post;
use Illuminate\Http\Request;
use Pharaonic\Laravel\ApiResponse\Response;

class PostController extends Controller
{
    public function index(Request $request)
    {
        $posts = Post::query()->where('title', 'like', '%'.$request->query('search').'%')->paginate(15);

        return Response::success(PostResource::collection($posts))->withQueryString(['search']);
    }

    public function store(StorePost $request)
    {
        $post = Post::query()->create($request->validated());

        return Response::created(new PostResource($post))
            ->message('Post created.')
            ->notify('Post created.', 'success')
            ->header('Location', url('/api/posts/'.$post->id));
    }

    public function destroy(Post $post)
    {
        $post->delete();

        return Response::noContent();
    }
}
```

### 2. Domain Errors With Stable Codes

Throw a domain exception from your services and map it once:

- ===Exception

  ```php title="app/Exceptions/InsufficientBalance.php"
  namespace App\Exceptions;

  use RuntimeException;

  class InsufficientBalance extends RuntimeException
  {
      public $balance;

      public function __construct(int $balance)
      {
          parent::__construct('Insufficient balance.');

          $this->balance = $balance;
      }
  }
  ```

- ===Mapper

  ```php title="app/Exceptions/InsufficientBalanceMapper.php"
  namespace App\Exceptions;

  use Illuminate\Http\Request;
  use Pharaonic\Laravel\ApiResponse\Response;
  use Pharaonic\Laravel\ApiResponse\Contracts\ExceptionMapper;
  use Throwable;

  class InsufficientBalanceMapper implements ExceptionMapper
  {
      public function map(Throwable $exception, Request $request): ?Response
      {
          return Response::error(__('payments.insufficient_balance'), 422)
              ->code('INSUFFICIENT_BALANCE')
              ->meta('balance', $exception->balance);
      }
  }
  ```

- ===Configuration

  ```php title="config/pharaonic/api-response.php"
  'exceptions' => [
      'paths' => ['api/*'],
      'mappers' => [
          App\Exceptions\InsufficientBalance::class => App\Exceptions\InsufficientBalanceMapper::class,
      ],
  ],
  ```

- ===Handler

  ```php title="app/Exceptions/Handler.php"
  public function render($request, Exception $exception)
  {
      return (new ExceptionRenderer)($exception, $request) ?? parent::render($request, $exception);
  }
  ```

Clients switch on `INSUFFICIENT_BALANCE`, while the message can be translated freely.

### 3. A Mobile Client With Its Own Shape

Serve the same endpoints in a compact shape to the mobile app, chosen by its media type:

- ===Profile

  ```php title="app/Http/Profiles/MobileProfile.php"
  namespace App\Http\Profiles;

  use Pharaonic\Laravel\ApiResponse\Profiles\Profile;

  class MobileProfile extends Profile
  {
      public function fields(): array
      {
          return array_merge(parent::fields(), ['success' => 'ok', 'data' => 'result']);
      }

      public function pagination(array $pagination): array
      {
          return array_intersect_key($pagination, array_flip(['type', 'pages', 'links']));
      }
  }
  ```

- ===Configuration

  ```php title="config/pharaonic/api-response.php"
  'profiles' => [
      'default' => Pharaonic\Laravel\ApiResponse\Profiles\Profile::class,
      'mobile' => App\Http\Profiles\MobileProfile::class,
  ],

  'content_negotiation' => [
      'enabled' => true,
      'media_types' => ['application/vnd.acme.mobile+json' => 'mobile'],
  ],
  ```

The web client keeps the default envelope; requests with `Accept: application/vnd.acme.mobile+json` get `ok` and `result`.

### 4. Tracing a Request Through the Logs

Register the middleware globally, then find every log line of a failing request from the ID the client reports:

```php title="app/Http/Kernel.php"
protected $middleware = [
    // ...
    \Pharaonic\Laravel\ApiResponse\Http\Middleware\AssignRequestId::class,
];
```

```json title="storage/logs/laravel.log" no-copy
[2026-11-24 10:00:00] local.ERROR: Payment gateway timed out {"order":42} {"request_id":"6f1c2a9e-2d4b-4c1f-9a43-3a8d0c7f5b21"}
```

### 5. A Versioned Response Macro

Give every response of a version the same header and metadata in one call:

```php title="app/Providers/AppServiceProvider.php"
use Pharaonic\Laravel\ApiResponse\Response;

public function boot()
{
    Response::macro('apiVersion', function (string $version) {
        return $this->header('X-API-Version', $version)->meta('api_version', $version);
    });
}
```

```php title="app/Http/Controllers/PostController.php"
return Response::success(PostResource::collection(Post::query()->paginate()))->apiVersion('2');
```

## Troubleshooting

### My exceptions are still rendered as HTML

The renderer only runs once you call it from your exception handler; see [Exception Rendering](#exceptions). It then renders requests that expect JSON or match `exceptions.paths`. Send `Accept: application/json`, or add your API's path to `exceptions.paths`.

### An exception keeps Laravel's own JSON shape

Exceptions that carry their own response are left to Laravel: `HttpResponseException`, exceptions with a `render()` method or that implement `Responsable`, and a `ValidationException` created with a response. Return a `Response` from that `render()` method, or map the exception with an `ExceptionMapper`.

### InvalidArgumentException: A success response needs a status below 400

`status()` refuses an error status on a success, and the other way round, so the `success` flag never contradicts the status. Start the response with `Response::error()` instead.

### InvalidArgumentException: An error response cannot carry data

An error carries its details in `errors()` or `meta()`, and a success never carries `errors()`. See [What Each Response Carries](#status-helpers).

### The data field is missing

`Response::success()` called without an argument sends no `data`. Pass the value, even `null`, or call `data()`.

### Pagination links lose a query parameter

Check `pagination.query_string.except`: denied keys are removed even when an allowlist names them. Check also whether the response calls `withoutQueryString()`, and whether `pagination.query_string.enabled` is `false`.

### Cursor paginators are sent as plain data

`cursorPaginate()` exists from Laravel 8.41, so it is supported on the 8.x line of this package and later.

### LogicException: withSEO() needs pharaonic/laravel-seo

Install `pharaonic/laravel-seo` 6.1 or later, or set `seo.missing_driver` to `ignore` to leave the field out.

### request_id is missing from the body

The request has no ID unless `AssignRequestId` ran for it. Register the middleware, and check `request_id.include_in_body`, the profile's `includesRequestId()` and `withoutRequestId()`.

### The client's X-Request-ID is not used

Incoming IDs are ignored unless `request_id.trust_incoming` is `true`, and even then an ID longer than `request_id.max_length` or with characters other than letters, digits, `.`, `_`, `:` and `-` is replaced.

### JsonException: Malformed UTF-8 characters

The data holds text that is not valid UTF-8, such as a binary column. Convert it or leave it out; the package never sends a partial body instead.

### A configuration change has no effect

Run `php artisan config:clear` after editing the published file when the configuration is cached.
