Skip to content
Laravel Packagev11.2.0MIT LicenseAI Ready

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.

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.

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.

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.

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.2, 8.3 or 8.4
  • Laravel 11.x

#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 lang/vendor/api-response to change a line or add a language:

Terminal
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 and the AssignRequestId middleware, both in bootstrap/app.php.

#Optional: SEO Tags

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

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

config/pharaonic/api-response.php
1return [
2 'default_profile' => 'default',
3 
4 'profiles' => [
5 'default' => Pharaonic\Laravel\ApiResponse\Profile::class,
6 ],
7 
8 'pagination' => [
9 'query_string' => true,
10 'sensitive_query' => ['token', 'api_key', 'access_token', 'password'],
11 ],
12 
13 'exceptions' => [
14 'paths' => ['api/*'],
15 ],
16 
17 'request_id' => [
18 'header' => 'X-Request-ID',
19 'trust_incoming' => false,
20 'logging' => true,
21 ],
22];
KeyDefaultDescription
default_profiledefaultThe profile a response uses unless it calls profile().
profilesdefault => Profile::classProfile names and their classes.
pagination.query_stringtrueKeep the request's query string in pagination links, unless a response calls withQueryString() or withoutQueryString().
pagination.sensitive_querytoken, api_key, access_token, passwordQuery keys never copied into a pagination link, compared without case.
exceptions.pathsapi/*Paths whose exceptions the registered renderer sends as JSON, besides requests that expect JSON.
request_id.headerX-Request-IDThe header AssignRequestId sends the ID in.
request_id.trust_incomingfalseReuse a valid incoming ID instead of generating one.
request_id.loggingtrueAdd 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

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.

app/Http/Controllers/PostController.php
1use App\Models\Post;
2use Pharaonic\Laravel\ApiResponse\Response;
3 
4public function show(Post $post)
5{
6 return Response::success($post);
7}
Response
1{
2 "success": true,
3 "message": null,
4 "data": {"id": 1, "title": "Hello"},
5 "meta": null
6}

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 and paginators.

#Message and Status

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

app/Http/Controllers/PostController.php
1return Response::success($post)
2 ->message('Post created.')
3 ->status(201)
4 ->notify('Post created.', 'success');

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

app/Http/Controllers/PostController.php
1$post->delete();
2 
3return Response::success()->status(204);

#Errors

app/Http/Controllers/PostController.php
1return Response::error('Post not found.', 404);
Response
1{
2 "success": false,
3 "message": "Post not found.",
4 "code": null,
5 "errors": null,
6 "meta": null
7}

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

app/Http/Controllers/PostController.php
1return Response::error('Validation failed.', 422)
2 ->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:

app/Http/Controllers/SessionController.php
1return 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:

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

Errors can carry metadata too. pagination is reserved for 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:

app/Http/Middleware/AddApiVersion.php
1namespace App\Http\Middleware;
2 
3use Closure;
4use Pharaonic\Laravel\ApiResponse\Response;
5 
6class AddApiVersion
7{
8 public function handle($request, Closure $next)
9 {
10 Response::shareMeta('version', '1.0');
11 
12 return $next($request);
13 }
14}
app/Http/Controllers/PostController.php
1public function show(Post $post)
2{
3 return Response::success($post); // "meta": {"version": "1.0"}
4}

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

app/Http/Controllers/PostController.php
1return Response::success($post)->status(201)->response()
2 ->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

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

#Simple

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

meta.pagination
1{
2 "type": "simple",
3 "pages": {"current": 1, "per_page": 15, "has_more": true},
4 "items": {"from": 1, "to": 15},
5 "links": {"prev": null, "next": "https://example.com/api/posts?page=2"}
6}

#Cursor

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

meta.pagination
1{
2 "type": "cursor",
3 "pages": {"per_page": 15, "has_more": true},
4 "cursors": {"current": null, "prev": null, "next": "eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0"},
5 "links": {"prev": null, "next": "https://example.com/api/posts?cursor=eyJpZCI6MTUs..."}
6}

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.

CallLinks keep
nothingwhat pagination.query_string says (true: every key)
withQueryString()every key
withQueryString(['search', 'sort'])only search and sort
withoutQueryString()only the page or cursor parameter
app/Http/Controllers/PostController.php
1return Response::success(Post::query()->paginate(15))
2 ->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.

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.

app/Http/Controllers/PostController.php
1use App\Http\Resources\PostResource;
2 
3return Response::success(new PostResource($post));

#Collections Over a Paginator

A resource collection over a paginator sends the transformed items and the pagination metadata, once:

app/Http/Controllers/PostController.php
1return 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:

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

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

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.

app/Http/Controllers/PostController.php
1return Response::success($post)
2 ->notify('Post created.', 'success')
3 ->notify('Your post is waiting for review.');
notifications
1[
2 {"type": "success", "message": "Post created."},
3 {"type": "info", "message": "Your post is waiting for review."}
4]

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:

app/Http/Controllers/PostController.php
1return Response::success($post)->notify(
2 'Your post is live.',
3 'success',
4 title: 'Published',
5 code: 'post.published',
6 action: ['label' => 'View post', 'url' => route('posts.show', $post)],
7 duration: 5000,
8 position: 'top-right',
9);
notifications
1[
2 {
3 "type": "success",
4 "title": "Published",
5 "message": "Your post is live.",
6 "code": "post.published",
7 "action": {"label": "View post", "url": "https://example.com/posts/1"},
8 "duration": 5000,
9 "position": "top-right"
10 }
11]
PartValue
titleA heading shown above the message.
codeA stable identifier the client can translate or act on, such as post.published.
actionA button: exactly a non-empty label and url.
durationHow long to show it, in milliseconds. 0 keeps it until it is dismissed; a negative value throws.
positiontop-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.

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:

app/Http/Profiles/MobileProfile.php
1namespace App\Http\Profiles;
2 
3use Pharaonic\Laravel\ApiResponse\Profile;
4 
5class MobileProfile extends Profile
6{
7 public function fields(): array
8 {
9 return ['data' => 'result', 'message' => 'msg'];
10 }
11 
12 public function requestIdInBody(): bool
13 {
14 return false;
15 }
16}

Register it under a name:

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

Choose it on a response:

app/Http/Controllers/PostController.php
1return Response::success($post)->profile('mobile');
Response
1{
2 "success": true,
3 "msg": null,
4 "result": {"id": 1},
5 "meta": null
6}

Without profile(), a response uses default_profile, and so do the errors of the exception renderer.

#Methods

MethodDefaultDescription
fields(): array[]The fields this profile renames, canonical name => sent name. Fields it leaves out keep their own name.
requestIdInBody(): booltrueWhether 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() 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 11, register it in withExceptions() in bootstrap/app.php. Laravel renders anything it returns null for:

bootstrap/app.php
1use Illuminate\Foundation\Configuration\Exceptions;
2use Pharaonic\Laravel\ApiResponse\ExceptionRenderer;
3 
4->withExceptions(function (Exceptions $exceptions) {
5 $exceptions->render(new ExceptionRenderer);
6})

#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

ExceptionStatusMessage
ValidationExceptionits status (422)its message, with errors from its bag
AuthenticationException401its message, or Unauthenticated.
AuthorizationException403its message, or This action is unauthorized.
ModelNotFoundException404Not Found.
TokenMismatchException419CSRF token mismatch.
any HTTP exception (missing route, 405, 429 throttling, abort())its statusits message, or the status text
anything else, app.debug off500Server Error.
Response
1{
2 "success": false,
3 "message": "The email field must be a valid email address.",
4 "code": null,
5 "errors": {"email": ["The email field must be a valid email address."]},
6 "meta": null
7}

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

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.

KeyEnglish
server_errorServer Error.
not_foundNot Found.
unauthenticatedUnauthenticated.
forbiddenThis action is unauthorized.
page_expiredCSRF token mismatch.
too_many_attemptsToo Many Attempts.
validationThe 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:

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

#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

Prepend it to the api group in bootstrap/app.php, or use prepend() to give every response the header:

bootstrap/app.php
1use Illuminate\Foundation\Configuration\Middleware;
2use Pharaonic\Laravel\ApiResponse\Http\Middleware\AssignRequestId;
3 
4->withMiddleware(function (Middleware $middleware) {
5 $middleware->api(prepend: [AssignRequestId::class]);
6})

Put it first, so responses 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 sends. A Response also carries it in the body, unless its profile returns false from requestIdInBody():

Response
1{
2 "success": true,
3 "message": null,
4 "data": {"id": 1},
5 "meta": null,
6 "request_id": "0f6b1a8e-3b8c-4f61-9d6a-0f0d9a3f3e21"
7}

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.

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

#SEO Tags

withSEO() adds the tags of pharaonic/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.

app/Http/Controllers/PageController.php
1seo()->title->set('About us');
2seo()->description->set('Who we are.');
3 
4return Response::success($page)->withSEO();

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

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

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

Terminal
php artisan boost:update

#What the Agent Learns

ResourceLoadedCovers
Guideline (resources/boost/guidelines/core.blade.php)In every sessionThe envelope, Response::success() and error(), paginators and query strings, and registering the exception renderer
Skill api-response-developmentWhen the agent works on API responsesEvery public method, the configuration, pagination shapes, profiles, shared metadata, the exception renderer, request IDs, SEO tags, pitfalls and testing
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

MethodDescriptionReturns
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

ClassDescription
ProfileThe base profile: fields() returns the renamed fields ([]), requestIdInBody() whether the body carries the request ID (true). Extend it for your own profiles.
ExceptionRendererInvokable: (new ExceptionRenderer)($exception, $request) returns the error response of an API request, or null to leave the exception to Laravel.
Http\Middleware\AssignRequestIdAssigns the request ID, sends it in the configured header and adds it to log records.
ApiResponseServiceProviderMerges and publishes the configuration (api-response-config), loads and publishes the translations (api-response-translations). Registered automatically.

#Exceptions Thrown

ExceptionWhen
InvalidArgumentExceptionA 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.
LogicExceptionwithSEO() without pharaonic/laravel-seo.

#Use Cases

#1. A CRUD Controller

One controller with the common responses:

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

A failed validate() becomes a 422 with the field errors once the exception renderer is registered.

#2. A Domain Error

Return the error from where you know it happened:

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

#3. A Mobile API With Its Own Field Names

app/Http/Profiles/MobileProfile.php
1namespace App\Http\Profiles;
2 
3use Pharaonic\Laravel\ApiResponse\Profile;
4 
5class MobileProfile extends Profile
6{
7 public function fields(): array
8 {
9 return ['data' => 'result'];
10 }
11 
12 public function requestIdInBody(): bool
13 {
14 return false;
15 }
16}
config/pharaonic/api-response.php
1'profiles' => [
2 'default' => Pharaonic\Laravel\ApiResponse\Profile::class,
3 'mobile' => App\Http\Profiles\MobileProfile::class,
4],
app/Http/Controllers/Mobile/FeedController.php
1return Response::success(Post::query()->latest()->simplePaginate(20))
2 ->profile('mobile')
3 ->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 in withExceptions() in bootstrap/app.php (Exception Rendering), 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.

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 (11.1 or later), or remove the withSEO() call.

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

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