# Laravel API Response documentation (v10.x)

> Canonical: https://pharaonic.dev/packages/laravel/api-response/10.x  
> Version: v10.x (latest release 10.2.0, 2026-11-26)  
> Install: composer require pharaonic/laravel-api-response  
> Repository: https://github.com/Pharaonic/laravel-api-response  
> All versions: https://pharaonic.dev/packages/laravel/api-response/13.x.md https://pharaonic.dev/packages/laravel/api-response/12.x.md https://pharaonic.dev/packages/laravel/api-response/11.x.md https://pharaonic.dev/packages/laravel/api-response/10.x.md https://pharaonic.dev/packages/laravel/api-response/9.x.md https://pharaonic.dev/packages/laravel/api-response/8.x.md https://pharaonic.dev/packages/laravel/api-response/7.x.md https://pharaonic.dev/packages/laravel/api-response/6.x.md

:::badges
- Laravel Package {color=blue}
- v10.2.0 {color=green}
- MIT License {color=purple}
- AI Ready {color=violet}
:::

# Laravel API Response

API Response gives your Laravel API one predictable JSON shape. You return `Response::success()` or `Response::error()` from a controller, chain what the response needs in any order, and Laravel builds the JSON response when it sends it. Resources and paginators are resolved for you, and notifications, request IDs and SEO tags appear only when you use them.

:::features
### One Envelope
success, message, data and meta for a success; success, message, code, errors and meta for an error. Data you set, even null or an empty list, is always sent.

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

### JSON Exceptions
A renderer you register yourself maps API exceptions to the error envelope in English or Arabic, keeps their headers and never leaks server errors.

### Profiles
A small profile class renames the envelope fields or leaves the request ID out, chosen per response or by default.

### Notifications
Attach success, info, warning and error messages for the client to show, in the order you add them, with an optional title, code, action, duration and position.

### Request IDs
A middleware sends a request ID in a header and the body, and adds it to your log records.

### Shared Metadata
Add metadata to one response, or share it from a middleware with every response of the request.

### SEO Tags
Send the page's tags from pharaonic/laravel-seo with one call, never by default.

### AI Ready
Laravel Boost guideline and skill included, so php artisan boost:install teaches your coding agent the package.
:::

:::success AI Ready
API Response ships Laravel Boost resources: a guideline loaded in every session and an `api-response-development` skill loaded when your agent works on API responses. Run `php artisan boost:install` and Claude Code, Cursor, Codex, Copilot or Gemini CLI build responses, errors and paginated lists the way the package expects. See [AI Ready](#ai-ready).
:::

:::info Nothing is rewritten behind your back
Only the responses you build with `Response` are shaped. `response()->json()`, views and redirects are untouched, and exception rendering stays off until you register it.
:::

:::warning A redesign in 6.1
6.1 replaces the 6.0 API: the `Response` class, status helpers, error codes, the old profile hooks, adapters, mappers, macros, content negotiation and the package translations are gone. Read the changelog before upgrading from 6.0.
:::

## Installation

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

### Requirements

- PHP 8.1, 8.2 or 8.3
- Laravel 10.x

### 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 `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: Exception Rendering and Request IDs

Two pieces are off until you register them in your application: the [exception renderer](#exceptions) in `app/Exceptions/Handler.php`, and the [`AssignRequestId` middleware](#request-ids) in `app/Http/Kernel.php`.

### Optional: SEO Tags

To send SEO tags with `withSEO()`, also install `pharaonic/laravel-seo` 10.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

The configuration is merged under `pharaonic.api-response` and read every time a response is built, so a change in a test or a service provider applies right away.

```php title="config/pharaonic/api-response.php"
return [
    'default_profile' => 'default',

    'profiles' => [
        'default' => Pharaonic\Laravel\ApiResponse\Profile::class,
    ],

    'pagination' => [
        'query_string' => true,
        'sensitive_query' => ['token', 'api_key', 'access_token', 'password'],
    ],

    'exceptions' => [
        'paths' => ['api/*'],
    ],

    'request_id' => [
        'header' => 'X-Request-ID',
        'trust_incoming' => false,
        'logging' => true,
    ],
];
```

| Key | Default | Description |
| --- | --- | --- |
| `default_profile` | `default` | The profile a response uses unless it calls `profile()`. |
| `profiles` | `default` => `Profile::class` | Profile names and their [classes](#profiles). |
| `pagination.query_string` | `true` | Keep the request's query string in pagination links, unless a response calls `withQueryString()` or `withoutQueryString()`. |
| `pagination.sensitive_query` | `token`, `api_key`, `access_token`, `password` | Query keys never copied into a pagination link, compared without case. |
| `exceptions.paths` | `api/*` | Paths whose exceptions the registered renderer sends as JSON, besides requests that expect JSON. |
| `request_id.header` | `X-Request-ID` | The header `AssignRequestId` sends the ID in. |
| `request_id.trust_incoming` | `false` | Reuse a valid incoming ID instead of generating one. |
| `request_id.logging` | `true` | Add the ID to `extra.request_id` of the default log channel's records. |

## Basic Usage

`Response::success()` and `Response::error()` start a response. Return it from a controller: it implements Laravel's `Responsable`, so Laravel builds the JSON response when it sends it.

### Success

:::tip Import the package's Response
Laravel has its own `Response` facade, so import `Pharaonic\Laravel\ApiResponse\Response` in each controller, or alias it (`use Pharaonic\Laravel\ApiResponse\Response as ApiResponse;`) where you also use Laravel's.
:::

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

public function show(Post $post)
{
    return Response::success($post);
}
```

```json title="Response" no-copy
{
  "success": true,
  "message": null,
  "data": {"id": 1, "title": "Hello"},
  "meta": null
}
```

`data` and `meta` are always sent; `data` as you set it: `null`, `[]`, `false` and `0` stay as they are. A model, a collection, an `Arrayable`, a `Jsonable` or any JSON-serializable value works, as do [API resources](#api-resources) and [paginators](#pagination).

### Message and Status

Every modifier returns the response, so you can chain them in any order:

```php title="app/Http/Controllers/PostController.php"
return Response::success($post)
    ->message('Post created.')
    ->status(201)
    ->notify('Post created.', 'success');
```

A success needs a 2xx status. `204` and `205` are sent without a body:

```php title="app/Http/Controllers/PostController.php"
$post->delete();

return Response::success()->status(204);
```

### Errors

```php title="app/Http/Controllers/PostController.php"
return Response::error('Post not found.', 404);
```

```json title="Response" no-copy
{
  "success": false,
  "message": "Post not found.",
  "code": null,
  "errors": null,
  "meta": null
}
```

An error defaults to `400` and needs a 4xx or 5xx status. `errors()` sets its details, such as the messages of each field:

```php title="app/Http/Controllers/PostController.php"
return Response::error('Validation failed.', 422)
    ->errors(['email' => ['The email field is required.']]);
```

`code()` sets a stable identifier the client can act on, such as `auth.expired`. Every error sends `code`, `null` until you set it, and a success never has one:

```php title="app/Http/Controllers/SessionController.php"
return Response::error('Your session has expired.', 401)->code('auth.expired');
```

A wrong status, or `errors()` or `code()` on a success, throws an `InvalidArgumentException` when you call it, so a response never says `success: true` with a 404.

### Metadata

`meta` is always sent after `data` or `errors`, as `null` until something is added. `meta()` adds one key and value, or an array of them; later values replace earlier ones:

```php title="app/Http/Controllers/PostController.php"
return Response::success($post)
    ->meta('version', '1.0')
    ->meta(['editable' => true]);
```

```json title="meta" no-copy
{"version": "1.0", "editable": true}
```

Errors can carry metadata too. `pagination` is reserved for [pagination](#pagination); `meta('pagination', ...)` throws an `InvalidArgumentException`.

### Shared Metadata

`Response::shareMeta()` adds metadata to every response of the current request, so a middleware can set what each controller response should carry:

```php title="app/Http/Middleware/AddApiVersion.php"
namespace App\Http\Middleware;

use Closure;
use Pharaonic\Laravel\ApiResponse\Response;

class AddApiVersion
{
    public function handle($request, Closure $next)
    {
        Response::shareMeta('version', '1.0');

        return $next($request);
    }
}
```

```php title="app/Http/Controllers/PostController.php"
public function show(Post $post)
{
    return Response::success($post); // "meta": {"version": "1.0"}
}
```

It takes a key and a value, or an array, like `meta()`. The metadata is stored on the request, so it never reaches another request, even in a long-running worker. It also reaches the errors of the [exception renderer](#exceptions). A resource's `with()` and `additional()` and the response's own `meta()` replace shared keys, and `pagination` comes last.

### Optional Fields

`notifications`, `seo` and `request_id` appear only when the response has them, in that order after `meta`.

### Building the Response Yourself

`response()` builds the HTTP response for the current request, when you need a concrete response object, for example to add a header:

```php title="app/Http/Controllers/PostController.php"
return Response::success($post)->status(201)->response()
    ->header('Location', url('/api/posts/'.$post->id));
```

`toResponse($request)` does the same for a given request. A response can be built more than once and gives the same result.

## Pagination

Pass a paginator, or a resource collection over one, and its items become `data` while its metadata goes to `meta.pagination`, grouped as `type`, `pages`, `items` or `cursors`, and `links`. Each type sends only what its paginator knows.

### Length-Aware

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

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

### Simple

`simplePaginate()` does not count rows, so there is no `items.total` or `pages.last`:

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

### Cursor

`cursorPaginate()` has no page numbers or totals. `cursors.current` is the cursor of this page (`null` on the first one):

```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=eyJpZCI6MTUs..."}
}
```

An empty page sends `data: []`, with `items.from` and `items.to` set to `null`.

### Query Strings

By default every pagination link keeps the request's query string, so `?search=php&page=2` links to `?search=php&page=3`. The page or cursor parameter is always the paginator's own.

| Call | Links keep |
| --- | --- |
| nothing | what `pagination.query_string` says (`true`: every key) |
| `withQueryString()` | every key |
| `withQueryString(['search', 'sort'])` | only `search` and `sort` |
| `withoutQueryString()` | only the page or cursor parameter |

```php title="app/Http/Controllers/PostController.php"
return Response::success(Post::query()->paginate(15))
    ->withQueryString(['search', 'sort']);
```

The keys in `pagination.sensitive_query` (`token`, `api_key`, `access_token`, `password`) are never copied into a link, even when you name them. The request and the paginator are never changed; only the links in the body are rebuilt.

:::tip A custom page name
`paginate(15, ['*'], 'p')` keeps `p` as the page parameter in every link.
:::

## API Resources

A `JsonResource` or a resource collection is resolved with the current request, so conditional attributes (`$this->when()`, `whenLoaded()`) behave as they do in Laravel. Its data is sent under `data` without Laravel's own wrapper, so there is never a `data.data`.

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

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

### Collections Over a Paginator

A resource collection over a paginator sends the transformed items and the [pagination metadata](#pagination), once:

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

### with(), additional() and withResponse()

What a resource returns from `with()` and sets with `additional()` goes to `meta`. Shared metadata comes first. The contents of a `meta` key are merged in and other keys keep their names. Then come the keys of the response's own `meta()`, which replace the resource's, and `pagination` comes last:

```php title="app/Http/Controllers/PostController.php"
return Response::success(PostResource::collection($posts)->additional(['meta' => ['count' => 5], 'version' => 2]));
```

```json title="meta" no-copy
{"version": 2, "count": 5}
```

A resource's `withResponse()` is called with the JSON response, so the headers it sets are sent.

:::info Eager loading is yours
The package only resolves the resource. Load relations in your query (`with('author')`) as you would for any resource.
:::

## Notifications

`notify()` attaches a message for the client to show, such as a toast. Call it as often as you need; notifications keep the order you add them in.

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

```json title="notifications" no-copy
[
  {"type": "success", "message": "Post created."},
  {"type": "info", "message": "Your post is waiting for review."}
]
```

The type is `success`, `info` (the default), `warning` or `error`; any other type throws an `InvalidArgumentException`. Errors can notify too.

### Title, code, action, duration and position

Every other part is optional and sent only when you give it, so pass the ones you need by name:

```php title="app/Http/Controllers/PostController.php"
return Response::success($post)->notify(
    'Your post is live.',
    'success',
    title: 'Published',
    code: 'post.published',
    action: ['label' => 'View post', 'url' => route('posts.show', $post)],
    duration: 5000,
    position: 'top-right',
);
```

```json title="notifications" no-copy
[
  {
    "type": "success",
    "title": "Published",
    "message": "Your post is live.",
    "code": "post.published",
    "action": {"label": "View post", "url": "https://example.com/posts/1"},
    "duration": 5000,
    "position": "top-right"
  }
]
```

| Part | Value |
| --- | --- |
| `title` | A heading shown above the message. |
| `code` | A stable identifier the client can translate or act on, such as `post.published`. |
| `action` | A button: exactly a non-empty `label` and `url`. |
| `duration` | How long to show it, in milliseconds. `0` keeps it until it is dismissed; a negative value throws. |
| `position` | `top-left`, `top-center`, `top-right`, `bottom-left`, `bottom-center` or `bottom-right`. |

The keys always come in the order `type`, `title`, `message`, `code`, `action`, `duration`, `position`. A wrong action, duration or position throws an `InvalidArgumentException`. Leave `duration` and `position` out to let the client decide.

:::info Response metadata only
Notifications are part of the response body. They have nothing to do with Laravel's mail, database or broadcast notifications, and nothing is stored or sent elsewhere.
:::

## Profiles

A profile is a class that extends `Pharaonic\Laravel\ApiResponse\Profile`. It can rename envelope fields and decide whether the body carries the request ID. Override only what differs from the defaults:

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

use Pharaonic\Laravel\ApiResponse\Profile;

class MobileProfile extends Profile
{
    public function fields(): array
    {
        return ['data' => 'result', 'message' => 'msg'];
    }

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

Register it under a name:

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

Choose it on a response:

```php title="app/Http/Controllers/PostController.php"
return Response::success($post)->profile('mobile');
```

```json title="Response" no-copy
{
  "success": true,
  "msg": null,
  "result": {"id": 1},
  "meta": null
}
```

Without `profile()`, a response uses `default_profile`, and so do the errors of the [exception renderer](#exceptions).

### Methods

| Method | Default | Description |
| --- | --- | --- |
| `fields(): array` | `[]` | The fields this profile renames, canonical name => sent name. Fields it leaves out keep their own name. |
| `requestIdInBody(): bool` | `true` | Whether the body carries `request_id` when the request has one. |

Profiles are built by the container for each response, so a constructor may type-hint dependencies such as the config repository.

### Rules

- Fields you can rename: `success`, `message`, `code`, `data`, `errors`, `meta`, `notifications`, `seo`, `request_id`.
- An unknown profile name, a class that does not extend `Profile`, an unknown field, an empty name, or two fields under the same name throw an `InvalidArgumentException` when the response is built.
- A profile never adds SEO tags; only [`withSEO()`](#seo) does.
- `withRequestId()` adds the request ID to one response even when its profile leaves it out.

## Exception Rendering

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

### Registering the Renderer

On Laravel 10, register it with `renderable()` in the `register()` method of your application's handler. Laravel renders anything it returns `null` for:

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

public function register(): void
{
    $this->renderable(new ExceptionRenderer);
}
```

### 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 keep Laravel's own rendering.

The renderer also returns `null`, leaving the exception to Laravel, for:

- exceptions that carry their own response: `HttpResponseException`, `Responsable` exceptions, exceptions with a `render()` method, and a `ValidationException` created with a response;
- an unexpected exception while `app.debug` is on, so you still get Laravel's debug output.

### Mappings

| Exception | Status | Message |
| --- | --- | --- |
| `ValidationException` | its status (422) | its message, with `errors` from its bag |
| `AuthenticationException` | 401 | its message, or Unauthenticated. |
| `AuthorizationException` | 403 | its message, or This action is unauthorized. |
| `ModelNotFoundException` | 404 | Not Found. |
| `TokenMismatchException` | 419 | CSRF token mismatch. |
| any HTTP exception (missing route, 405, 429 throttling, `abort()`) | its status | its message, or the status text |
| anything else, `app.debug` off | 500 | Server Error. |

```json title="Response" no-copy
{
  "success": false,
  "message": "The email field must be a valid email address.",
  "code": null,
  "errors": {"email": ["The email field must be a valid email address."]},
  "meta": null
}
```

The renderer sets no code, so `code` is always `null` on the errors it renders. An HTTP exception keeps its headers, such as `Retry-After` and `X-RateLimit-*` from throttling, `Allow` from a 405, or a `WWW-Authenticate` challenge. When the [`AssignRequestId` middleware](#request-ids) runs, the error carries the request ID in its header and body like any other response, and metadata shared with `Response::shareMeta()` joins its `meta`.

:::danger Nothing about a server error is sent
A 500 sends only "Server Error.": no exception class, message, file, trace or SQL. A missing model sends only "Not Found.", never the model class or the keys.
:::

### Translated Messages

The package's messages follow the application locale, from `api-response::messages`. English and Arabic ship with the package; a locale without a line falls back to English.

| Key | English |
| --- | --- |
| `server_error` | Server Error. |
| `not_found` | Not Found. |
| `unauthenticated` | Unauthenticated. |
| `forbidden` | This action is unauthorized. |
| `page_expired` | CSRF token mismatch. |
| `too_many_attempts` | Too Many Attempts. |
| `validation` | The given data was invalid. (a validation error with that message; Laravel 9 sends the first error instead) |
| `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., Too Many Attempts., CSRF token mismatch.) are translated through the same lines. A validation error's message is its first error, which Laravel translates with its own validation lines. Any other exception message is yours and is sent as it is, so translate it where you throw: `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="lang/vendor/api-response/fr/messages.php"
return [
    'server_error' => 'Erreur du serveur.',
    'not_found' => 'Introuvable.',
    // ...
];
```

## 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 to your log records.

### Registering the Middleware

Add it to the `api` group, or globally to give every response the header:

```php title="app/Http/Kernel.php"
protected $middlewareGroups = [
    'api' => [
        \Pharaonic\Laravel\ApiResponse\Http\Middleware\AssignRequestId::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];
```

Put it first in the group, so responses its later middleware return, such as a 429 from throttling, get the header too.

### Header and Body

Every response that passes through the middleware gets the header, including errors the [exception renderer](#exceptions) sends. A `Response` also carries it in the body, unless its [profile](#profiles) returns `false` from `requestIdInBody()`:

```json title="Response" no-copy
{
  "success": true,
  "message": null,
  "data": {"id": 1},
  "meta": null,
  "request_id": "0f6b1a8e-3b8c-4f61-9d6a-0f0d9a3f3e21"
}
```

A response built outside the middleware has no request ID and no `request_id` field.

### Incoming IDs

An incoming `X-Request-ID` is untrusted and ignored by default: every request gets a new UUID. Set `request_id.trust_incoming` to `true` to reuse it, for example behind a gateway that assigns IDs. Even then, it is reused only when it is 1 to 128 letters, digits, `.`, `_`, `:` or `-`; anything else is replaced by a UUID.

### Log Records

With `request_id.logging` on, every record of the default log channel gets `extra.request_id`. The ID is read from the current request when the record is written and lives only on that request, so a long-running worker never logs the ID of an earlier request.

```php title="app/Http/Controllers/OrderController.php"
Log::info('Order placed.'); // extra: {"request_id": "0f6b1a8e-..."}
```

## SEO Tags

`withSEO()` adds the tags of [pharaonic/laravel-seo](https://pharaonic.dev/packages/laravel/seo) to the response, under `seo`. It is optional: the package does not require laravel-seo, and a response never carries SEO tags without this call, whatever its profile or the configuration say.

```php title="app/Http/Controllers/PageController.php"
seo()->title->set('About us');
seo()->description->set('Who we are.');

return Response::success($page)->withSEO();
```

The tags are what `seo()->toArray()` returns (laravel-seo 10.1 or later), read when the response is built, so set them anywhere before you return.

:::warning laravel-seo must be installed
`withSEO()` without laravel-seo throws a `LogicException` that tells you to run `composer require pharaonic/laravel-seo`, instead of sending a response without the tags you asked for.
:::

## AI Ready

API Response is AI ready. It ships [Laravel Boost](https://laravel.com/docs/boost) resources, so the coding agent in your application (Claude Code, Cursor, Codex, Copilot, Gemini CLI, Junie…) knows how to use the package.

### Install

With Laravel Boost in your application, run:

```bash title="Terminal" no-line-numbers
php artisan boost:install
```

Boost finds the package's guideline and skill in `vendor/` and adds them for the agents you choose. After updating the package, refresh them with:

```bash title="Terminal" no-line-numbers
php artisan boost:update
```

### What the Agent Learns

| Resource | Loaded | Covers |
| --- | --- | --- |
| Guideline (`resources/boost/guidelines/core.blade.php`) | In every session | The envelope, `Response::success()` and `error()`, paginators and query strings, and registering the exception renderer |
| Skill `api-response-development` | When the agent works on API responses | Every public method, the configuration, pagination shapes, profiles, shared metadata, the exception renderer, request IDs, SEO tags, pitfalls and testing |

:::tip Keep Them Current
Add `@php artisan boost:update --ansi` to your Composer `post-update-cmd` scripts so the agent always matches the installed release.
:::

## Methods & Classes

All classes are in the `Pharaonic\Laravel\ApiResponse` namespace. Classes under `Support` are internal.

### Response

| Method | Description | Returns |
| --- | --- | --- |
| `Response::success(mixed $data = null)` | A 200 success carrying the data. | `Response` |
| `Response::error(string $message, int $status = 400)` | An error; the status must be 400 to 599. | `Response` |
| `Response::shareMeta(string\|array $key, mixed $value = null)` | Adds metadata to every response of the current request, such as from a middleware. `pagination` is reserved. | `void` |
| `message(?string $message)` | Sets the message. | `Response` |
| `status(int $status)` | Sets the status: 2xx for a success, 4xx or 5xx for an error. 204 and 205 have no body. | `Response` |
| `code(?string $code)` | Sets the code of an error, sent as `null` until set; refused on a success. | `Response` |
| `errors(?array $errors)` | Sets the errors of an error; refused on a success. | `Response` |
| `meta(string\|array $key, mixed $value = null)` | Adds metadata: one key and value, or an array of them. `pagination` is reserved. | `Response` |
| `notify(string $message, string $type = 'info', ?string $title = null, ?string $code = null, ?array $action = null, ?int $duration = null, ?string $position = null)` | Adds a notification: `success`, `info`, `warning` or `error`, with an optional title, code, action (`label` and `url`), duration in milliseconds and position. | `Response` |
| `profile(string $name)` | Uses a profile registered in `pharaonic.api-response.profiles`. | `Response` |
| `withSEO()` | Adds the tags of pharaonic/laravel-seo. | `Response` |
| `withRequestId()` | Adds the request ID to the body even when the profile leaves it out. | `Response` |
| `withQueryString(?array $only = null)` | Keeps every query key, or only the given ones, in pagination links. | `Response` |
| `withoutQueryString()` | Keeps only the page or cursor parameter in pagination links. | `Response` |
| `response()` | Builds the HTTP response for the current request. | `Symfony\Component\HttpFoundation\Response` |
| `toResponse($request)` | Builds the HTTP response for the given request (`Responsable`). | `Symfony\Component\HttpFoundation\Response` |

### Other Classes

| Class | Description |
| --- | --- |
| `Profile` | The base profile: `fields()` returns the renamed fields (`[]`), `requestIdInBody()` whether the body carries the request ID (`true`). Extend it for your own profiles. |
| `ExceptionRenderer` | Invokable: `(new ExceptionRenderer)($exception, $request)` returns the error response of an API request, or `null` to leave the exception to Laravel. |
| `Http\Middleware\AssignRequestId` | Assigns the request ID, sends it in the configured header and adds it to log records. |
| `ApiResponseServiceProvider` | Merges and publishes the configuration (`api-response-config`), loads and publishes the translations (`api-response-translations`). Registered automatically. |

### Exceptions Thrown

| Exception | When |
| --- | --- |
| `InvalidArgumentException` | A status outside the allowed range, `errors()` or `code()` on a success, `meta('pagination', ...)` or `shareMeta('pagination', ...)`, an unknown notification type or position, a notification action without exactly a `label` and `url`, a negative notification duration, an unknown profile, a profile class that does not extend `Profile`, or an invalid profile field. |
| `LogicException` | `withSEO()` without pharaonic/laravel-seo. |

## Use Cases

### 1. A CRUD Controller

One controller with the common responses:

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

use App\Http\Resources\PostResource;
use App\Models\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(Request $request)
    {
        $post = Post::query()->create($request->validate(['title' => 'required|string']));

        return Response::success(new PostResource($post))
            ->status(201)
            ->message('Post created.')
            ->notify('Post created.', 'success');
    }

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

        return Response::success()->status(204);
    }
}
```

A failed `validate()` becomes a 422 with the field errors once the [exception renderer](#exceptions) is registered.

### 2. A Domain Error

Return the error from where you know it happened:

```php title="app/Http/Controllers/OrderController.php"
if ($user->balance < $total) {
    return Response::error('Insufficient balance.', 422)
        ->errors(['balance' => ['Your balance is too low.']])
        ->meta(['balance' => $user->balance, 'required' => $total])
        ->notify('Top up your wallet to continue.', 'warning');
}
```

### 3. A Mobile API With Its Own Field Names

- ===Profile

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

  use Pharaonic\Laravel\ApiResponse\Profile;

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

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

- ===Configuration

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

- ===Controller

  ```php title="app/Http/Controllers/Mobile/FeedController.php"
  return Response::success(Post::query()->latest()->simplePaginate(20))
      ->profile('mobile')
      ->withoutQueryString();
  ```

### 4. Tracing a Request Through the Logs

With `AssignRequestId` in the `api` group, a client that reports an error sends you the `X-Request-ID` it received, and you find every log line of that request by `extra.request_id`.

## Troubleshooting

### My exceptions still render as HTML

The renderer is not registered, or the request is not an API request. Register it with `renderable()` in your handler's `register()` ([Exception Rendering](#exceptions)), and send `Accept: application/json` or add the path to `exceptions.paths`.

### A 500 shows Laravel's debug output instead of the envelope

That happens while `app.debug` is on, so you can see the exception. With `app.debug` off, a 500 sends "Server Error." in the envelope.

### An exception keeps its own JSON

Exceptions with a `render()` method or their own response are left to Laravel. Return a `Response` from that `render()` method if you want the envelope.

### InvalidArgumentException: The response profile [...] is not defined

The profile name passed to `profile()`, or `default_profile`, is not a key of `pharaonic.api-response.profiles`. If you published the configuration before adding a profile, add it to the published file.

### There is no request_id in the body

The request did not pass through `AssignRequestId`, or the profile's `requestIdInBody()` returns `false`. Add the middleware, or call `withRequestId()` on that response.

### Pagination links lose a query parameter

The key is in `pagination.sensitive_query`, the response calls `withQueryString([...])` without it, or `pagination.query_string` is `false`.

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

Install it with `composer require pharaonic/laravel-seo` (10.1 or later), or remove the `withSEO()` call.
