Skip to content
Laravel Packagev6.0.0MIT License

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.

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.

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

Terminal
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:

Terminal
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:

Terminal
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:

Terminal
composer require pharaonic/laravel-seo
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:

config/pharaonic/api-response.php
1'envelope' => [
2 'fields' => [
3 'success' => 'ok',
4 'message' => 'message',
5 'code' => 'code',
6 'data' => 'result',
7 'errors' => 'errors',
8 'meta' => 'meta',
9 'notifications' => 'notifications',
10 'seo' => 'seo',
11 'request_id' => 'request_id',
12 ],
13],
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.

app/Http/Controllers/PostController.php
1use App\Post;
2use Pharaonic\Laravel\ApiResponse\Response;
3 
4class PostController extends Controller
5{
6 public function show(Post $post)
7 {
8 return Response::success($post)
9 ->message('Post retrieved successfully.')
10 ->meta('version', '1.0');
11 }
12}
Response
1{
2 "success": true,
3 "message": "Post retrieved successfully.",
4 "data": {"id": 1, "title": "Laravel SEO"},
5 "meta": {"version": "1.0"}
6}
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:

app/Http/Controllers/PaymentController.php
1return Response::error('Insufficient balance.', 422)->code('INSUFFICIENT_BALANCE');
Response
1{
2 "success": false,
3 "message": "Insufficient balance.",
4 "code": "INSUFFICIENT_BALANCE"
5}

#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 '':

1Response::success(); // {"success":true}
2Response::success(null); // {"success":true,"data":null}
3Response::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:

1Response::success($post)->message('Saved.')->notify('Saved.', 'success');
2Response::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:

1$response = Response::success(['ok' => true])->response();
2 
3$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
app/Http/Controllers/RegisterController.php
1return Response::validationError(['email' => ['The email field is required.']]);
Response
1{
2 "success": false,
3 "message": "The given data was invalid.",
4 "code": "VALIDATION_ERROR",
5 "errors": {"email": ["The email field is required."]}
6}

#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.

1Response::error('Payment failed.', 402)->meta('retry_after', 30); // fine
2Response::error('Payment failed.', 402)->data($order); // InvalidArgumentException
3Response::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 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.

1Response::error('Conflict.')->status(409); // 409, "success": false
2Response::success($post)->status(203); // 203, "success": true
3Response::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:

1Response::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.

1return 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.

#Length-Aware Paginators

paginate(), and a LengthAwarePaginator you build yourself:

app/Http/Controllers/PostController.php
1return Response::success(Post::query()->paginate(15));
Response
1{
2 "success": true,
3 "data": [{"id": 1, "title": "First post"}],
4 "meta": {
5 "pagination": {
6 "type": "length_aware",
7 "pages": {
8 "current": 1,
9 "last": 10,
10 "per_page": 15,
11 "has_more": true
12 },
13 "items": {
14 "total": 150,
15 "from": 1,
16 "to": 15
17 },
18 "links": {
19 "first": "https://example.com/api/posts?page=1",
20 "last": "https://example.com/api/posts?page=10",
21 "prev": null,
22 "next": "https://example.com/api/posts?page=2"
23 }
24 }
25 }
26}

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:

meta.pagination
1{
2 "type": "simple",
3 "pages": {
4 "current": 2,
5 "per_page": 15,
6 "has_more": true
7 },
8 "items": {
9 "from": 16,
10 "to": 30
11 },
12 "links": {
13 "prev": "https://example.com/api/posts?page=1",
14 "next": "https://example.com/api/posts?page=3"
15 }
16}

#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:

meta.pagination
1{
2 "type": "cursor",
3 "pages": {
4 "per_page": 15,
5 "has_more": true
6 },
7 "cursors": {
8 "current": null,
9 "prev": null,
10 "next": "eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0"
11 },
12 "links": {
13 "prev": null,
14 "next": "https://example.com/api/posts?cursor=eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0"
15 }
16}

#Custom Page Names

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

1return Response::success(Post::query()->paginate(15, ['*'], 'p'));
2// "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:

app/Pagination/RemotePageAdapter.php
1use App\Remote\RemotePage;
2use Closure;
3use Pharaonic\Laravel\ApiResponse\Contracts\PaginationAdapter;
4 
5class RemotePageAdapter implements PaginationAdapter
6{
7 public function supports(object $paginator): bool
8 {
9 return $paginator instanceof RemotePage;
10 }
11 
12 public function items(object $paginator): mixed
13 {
14 return $paginator->items;
15 }
16 
17 public function meta(object $paginator, Closure $url): array
18 {
19 return [
20 'type' => 'token',
21 'pages' => ['has_more' => $paginator->nextToken !== null],
22 'links' => [
23 'next' => $paginator->nextToken === null
24 ? null
25 : $url($paginator->path.'?page_token='.$paginator->nextToken, 'page_token'),
26 ],
27 ];
28 }
29}
config/pharaonic/api-response.php
1'pagination' => [
2 // ...
3 'adapters' => [App\Pagination\RemotePageAdapter::class],
4],

#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:

1return 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.

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

1// Every key except the denied ones (the default).
2->withQueryString()
3 
4// Only these keys, still without the denied ones.
5->withQueryString(['search', 'sort'])
6 
7// No extra keys; the page or cursor parameter stays.
8->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:

config/pharaonic/api-response.php
1'query_string' => [
2 'enabled' => true,
3 'except' => ['token', 'api_key', 'access_token', 'password', 'signature'],
4],
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

app/Http/Controllers/PostController.php
1use App\Http\Resources\PostResource;
2 
3return 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:

1return Response::success(PostResource::collection(Post::query()->paginate(15)));
2return 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:

app/Http/Resources/PostResource.php
1public function with($request)
2{
3 return [
4 'meta' => ['resource' => 'post'],
5 'links' => ['self' => url('/api/posts/'.$this->id)],
6 ];
7}
Response
1{
2 "success": true,
3 "data": {"id": 1, "title": "Laravel SEO"},
4 "meta": {
5 "links": {"self": "https://example.com/api/posts/1"},
6 "resource": "post"
7 }
8}

#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:

app/Http/Resources/PostCollection.php
1public function paginationInformation($request, $paginated, $default)
2{
3 $default['pagination']['label'] = 'posts';
4 
5 return $default;
6}

#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.

app/Http/Controllers/PostController.php
1return Response::created(new PostResource($post))
2 ->notify('Post created.', 'success')
3 ->notify('Waiting for review.');
Response
1{
2 "success": true,
3 "data": {"id": 1, "title": "Laravel SEO"},
4 "notifications": [
5 {"type": "success", "message": "Post created."},
6 {"type": "info", "message": "Waiting for review."}
7 ]
8}

#Structured Fields

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

1return Response::success(new PostResource($post))->notify(
2 message: 'Post created successfully.',
3 type: 'success',
4 title: 'Done',
5 duration: 5000,
6 data: ['post_id' => $post->id],
7);

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:

config/pharaonic/api-response.php
1'notifications' => [
2 'default_type' => 'info',
3 'types' => ['success', 'error', 'warning', 'info', 'celebrate'],
4],

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 to send notifications in another shape:

app/Http/Profiles/MobileProfile.php
1public function notification(array $notification): array
2{
3 return ['text' => $notification['message'], 'kind' => $notification['type']];
4}
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:

app/Http/Profiles/MobileProfile.php
1namespace App\Http\Profiles;
2 
3use Pharaonic\Laravel\ApiResponse\Profiles\Profile;
4 
5class MobileProfile extends Profile
6{
7 public function fields(): array
8 {
9 return array_merge(parent::fields(), ['success' => 'ok', 'data' => 'result']);
10 }
11 
12 public function pagination(array $pagination): array
13 {
14 return array_intersect_key($pagination, array_flip(['type', 'pages', 'cursors']));
15 }
16 
17 public function headers(): array
18 {
19 return ['X-Profile' => 'mobile'];
20 }
21 
22 public function includesRequestId(): bool
23 {
24 return false;
25 }
26}

Register it under a name:

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

#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:

app/Http/Profiles/RawProfile.php
1class RawProfile extends Profile
2{
3 public function body(array $parts): mixed
4 {
5 return $parts['data'] ?? null;
6 }
7}

#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.

routes/api.php
1use Pharaonic\Laravel\ApiResponse\Http\Middleware\UseResponseProfile;
2 
3Route::middleware(UseResponseProfile::class.':mobile')->group(function () {
4 Route::get('feed', 'FeedController@index');
5});

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:

config/pharaonic/api-response.php
1'content_negotiation' => [
2 'enabled' => true,
3 'media_types' => [
4 'application/vnd.acme.mobile+json' => 'mobile',
5 ],
6],
Terminal
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:

1return Response::success($posts)
2 ->header('X-API-Version', '1')
3 ->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:

1return Response::success($post)
2 ->when($request->user()->isAdmin(), fn (Response $response) => $response->meta('audit', $post->audits))
3 ->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:

1return Response::success(Post::query()->paginate(15))
2 ->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:

app/Providers/AppServiceProvider.php
1use Pharaonic\Laravel\ApiResponse\Response;
2 
3public function boot()
4{
5 Response::macro('version', function (string $version) {
6 return $this->header('X-API-Version', $version)->meta('version', $version);
7 });
8}
1return 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.

config/pharaonic/api-response.php
1'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:

app/Exceptions/Handler.php
1use Exception;
2use Pharaonic\Laravel\ApiResponse\ExceptionRenderer;
3 
4public function render($request, Exception $exception)
5{
6 return (new ExceptionRenderer)($exception, $request) ?? parent::render($request, $exception);
7}

#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 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:

Response
1{
2 "success": false,
3 "message": "A request with this idempotency key is still being processed.",
4 "code": "IDEMPOTENCY_IN_PROGRESS",
5 "request_id": "9b1d…"
6}

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:

Terminal
php artisan vendor:publish --tag=api-response-translations
resources/lang/vendor/api-response/fr/messages.php
1return [
2 'not_found' => 'Introuvable.',
3 // ...
4];

#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.

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:

app/Exceptions/InsufficientBalanceMapper.php
1namespace App\Exceptions;
2 
3use Illuminate\Http\Request;
4use Pharaonic\Laravel\ApiResponse\Response;
5use Pharaonic\Laravel\ApiResponse\Contracts\ExceptionMapper;
6use Throwable;
7 
8class InsufficientBalanceMapper implements ExceptionMapper
9{
10 public function map(Throwable $exception, Request $request): ?Response
11 {
12 return Response::error('Insufficient balance.', 422)
13 ->code('INSUFFICIENT_BALANCE')
14 ->meta('balance', $exception->balance);
15 }
16}
config/pharaonic/api-response.php
1'exceptions' => [
2 'paths' => ['api/*'],
3 'mappers' => [
4 App\Exceptions\InsufficientBalance::class => App\Exceptions\InsufficientBalanceMapper::class,
5 ],
6],

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.

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:

app/Http/Kernel.php
1protected $middleware = [
2 // ...
3 \Pharaonic\Laravel\ApiResponse\Http\Middleware\AssignRequestId::class,
4];

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:

app/Support/RequestIdGenerator.php
1namespace App\Support;
2 
3use Illuminate\Support\Str;
4 
5class RequestIdGenerator
6{
7 public function __invoke(): string
8 {
9 return 'req_'.Str::random(24);
10 }
11}

#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:

1return Response::success($post)->withoutRequestId();
2return 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.

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.

app/Http/Controllers/PostController.php
1seo()->title->set($post->title);
2seo()->description->set($post->excerpt);
3 
4return Response::success(new PostResource($post))->withSEO();
Response
1{
2 "success": true,
3 "data": {"id": 1, "title": "Laravel SEO"},
4 "seo": {"title": "Laravel SEO", "description": "Meta tags from code."}
5}

#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:

config/pharaonic/api-response.php
1'seo' => [
2 'missing_driver' => 'ignore',
3],

#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 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:

app/Http/Controllers/PostController.php
1namespace App\Http\Controllers;
2 
3use App\Http\Requests\StorePost;
4use App\Http\Resources\PostResource;
5use App\Post;
6use Illuminate\Http\Request;
7use Pharaonic\Laravel\ApiResponse\Response;
8 
9class PostController extends Controller
10{
11 public function index(Request $request)
12 {
13 $posts = Post::query()->where('title', 'like', '%'.$request->query('search').'%')->paginate(15);
14 
15 return Response::success(PostResource::collection($posts))->withQueryString(['search']);
16 }
17 
18 public function store(StorePost $request)
19 {
20 $post = Post::query()->create($request->validated());
21 
22 return Response::created(new PostResource($post))
23 ->message('Post created.')
24 ->notify('Post created.', 'success')
25 ->header('Location', url('/api/posts/'.$post->id));
26 }
27 
28 public function destroy(Post $post)
29 {
30 $post->delete();
31 
32 return Response::noContent();
33 }
34}

#2. Domain Errors With Stable Codes

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

app/Exceptions/InsufficientBalance.php
1namespace App\Exceptions;
2 
3use RuntimeException;
4 
5class InsufficientBalance extends RuntimeException
6{
7 public $balance;
8 
9 public function __construct(int $balance)
10 {
11 parent::__construct('Insufficient balance.');
12 
13 $this->balance = $balance;
14 }
15}
app/Exceptions/InsufficientBalanceMapper.php
1namespace App\Exceptions;
2 
3use Illuminate\Http\Request;
4use Pharaonic\Laravel\ApiResponse\Response;
5use Pharaonic\Laravel\ApiResponse\Contracts\ExceptionMapper;
6use Throwable;
7 
8class InsufficientBalanceMapper implements ExceptionMapper
9{
10 public function map(Throwable $exception, Request $request): ?Response
11 {
12 return Response::error(__('payments.insufficient_balance'), 422)
13 ->code('INSUFFICIENT_BALANCE')
14 ->meta('balance', $exception->balance);
15 }
16}
config/pharaonic/api-response.php
1'exceptions' => [
2 'paths' => ['api/*'],
3 'mappers' => [
4 App\Exceptions\InsufficientBalance::class => App\Exceptions\InsufficientBalanceMapper::class,
5 ],
6],
app/Exceptions/Handler.php
1public function render($request, Exception $exception)
2{
3 return (new ExceptionRenderer)($exception, $request) ?? parent::render($request, $exception);
4}

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:

app/Http/Profiles/MobileProfile.php
1namespace App\Http\Profiles;
2 
3use Pharaonic\Laravel\ApiResponse\Profiles\Profile;
4 
5class MobileProfile extends Profile
6{
7 public function fields(): array
8 {
9 return array_merge(parent::fields(), ['success' => 'ok', 'data' => 'result']);
10 }
11 
12 public function pagination(array $pagination): array
13 {
14 return array_intersect_key($pagination, array_flip(['type', 'pages', 'links']));
15 }
16}
config/pharaonic/api-response.php
1'profiles' => [
2 'default' => Pharaonic\Laravel\ApiResponse\Profiles\Profile::class,
3 'mobile' => App\Http\Profiles\MobileProfile::class,
4],
5 
6'content_negotiation' => [
7 'enabled' => true,
8 'media_types' => ['application/vnd.acme.mobile+json' => 'mobile'],
9],

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:

app/Http/Kernel.php
1protected $middleware = [
2 // ...
3 \Pharaonic\Laravel\ApiResponse\Http\Middleware\AssignRequestId::class,
4];
storage/logs/laravel.log
1[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:

app/Providers/AppServiceProvider.php
1use Pharaonic\Laravel\ApiResponse\Response;
2 
3public function boot()
4{
5 Response::macro('apiVersion', function (string $version) {
6 return $this->header('X-API-Version', $version)->meta('api_version', $version);
7 });
8}
app/Http/Controllers/PostController.php
1return 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. 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.

#The data field is missing

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

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.

Contributors

Amazing people who made this package possible

This package wouldn't exist without the contributions of our amazing community. A huge thank you to everyone who has helped improve Laravel API Response!

Moamen Eltouny

@MoamenEltouny

4 contributions

Want to Contribute?

We welcome contributions from everyone! Whether it's bug fixes, new features, or documentation improvements - every contribution counts.

Was this page helpful?

Something wrong or missing? Report it on GitHub .