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, 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.
Request IDs
A middleware sends a request ID in a header and the body, and adds it to your log records.
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.
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.0 or 8.1
- Laravel 8.x (8.75 or later)
#Composer Installation
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:
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:
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 in app/Exceptions/Handler.php, and the AssignRequestId middleware in app/Http/Kernel.php.
#Optional: SEO Tags
To send SEO tags with withSEO(), also install pharaonic/laravel-seo 8.1 or later:
composer require pharaonic/laravel-seoYou'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.
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];| Key | Default | Description |
|---|---|---|
default_profile | default | The profile a response uses unless it calls profile(). |
profiles | default => Profile::class | Profile names and their classes. |
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
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.
1use App\Models\Post;2use Pharaonic\Laravel\ApiResponse\Response;3 4public function show(Post $post)5{6 return Response::success($post);7}1{2 "success": true,3 "message": null,4 "data": {"id": 1, "title": "Hello"},5 "meta": null6}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:
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:
1$post->delete();2 3return Response::success()->status(204);#Errors
1return Response::error('Post not found.', 404);1{2 "success": false,3 "message": "Post not found.",4 "errors": null,5 "meta": null6}An error defaults to 400 and needs a 4xx or 5xx status. errors() sets its details, such as the messages of each field:
1return Response::error('Validation failed.', 422)2 ->errors(['email' => ['The email field is required.']]);A wrong status, or errors() 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:
1return Response::success($post)2 ->meta('version', '1.0')3 ->meta(['editable' => true]);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:
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}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:
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. Each type sends only what its paginator knows.
#Length-Aware
1return Response::success(Post::query()->paginate(15)); 1{ 2 "success": true, 3 "message": null, 4 "data": [{"id": 16, "title": "..."}], 5 "meta": { 6 "pagination": { 7 "type": "length_aware", 8 "current_page": 2, 9 "last_page": 4,10 "per_page": 15,11 "total": 52,12 "from": 16,13 "to": 30,14 "has_more_pages": true,15 "links": {16 "first": "https://example.com/api/posts?page=1",17 "last": "https://example.com/api/posts?page=4",18 "prev": "https://example.com/api/posts?page=1",19 "next": "https://example.com/api/posts?page=3"20 }21 }22 }23}#Simple
simplePaginate() does not count rows, so there is no total or last_page:
1{2 "type": "simple",3 "current_page": 1,4 "per_page": 15,5 "from": 1,6 "to": 15,7 "has_more_pages": true,8 "links": {"prev": null, "next": "https://example.com/api/posts?page=2"}9}#Cursor
cursorPaginate() has no page numbers or totals:
1{2 "type": "cursor",3 "per_page": 15,4 "next_cursor": "eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0",5 "prev_cursor": null,6 "has_more_pages": true,7 "links": {"prev": null, "next": "https://example.com/api/posts?cursor=eyJpZCI6MTUs..."}8}An empty page sends data: [], with from and 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 |
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.
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.
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:
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:
1return Response::success(PostResource::collection($posts)->additional(['meta' => ['count' => 5], 'version' => 2]));1{"version": 2, "count": 5}A resource's withResponse() is called with the JSON response, so the headers it sets are sent.
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.
1return Response::success($post)2 ->notify('Post created.', 'success')3 ->notify('Your post is waiting for review.');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.
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:
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(): bool13 {14 return false;15 }16}Register it under a name:
1'profiles' => [2 'default' => Pharaonic\Laravel\ApiResponse\Profile::class,3 'mobile' => App\Http\Profiles\MobileProfile::class,4],Choose it on a response:
1return Response::success($post)->profile('mobile');1{2 "success": true,3 "msg": null,4 "result": {"id": 1},5 "meta": null6}Without profile(), a response uses default_profile, and so do the errors of the exception renderer.
#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,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 anInvalidArgumentExceptionwhen 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 8, register it with renderable() in the register() method of your application's handler. Laravel renders anything it returns null for:
1use Pharaonic\Laravel\ApiResponse\ExceptionRenderer;2 3public function register()4{5 $this->renderable(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,Responsableexceptions, exceptions with arender()method, and aValidationExceptioncreated with a response; - an unexpected exception while
app.debugis 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. |
1{2 "success": false,3 "message": "The given data was invalid.",4 "errors": {"email": ["The email must be a valid email address."]},5 "meta": null6}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.
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. |
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., CSRF token mismatch.) are translated through the same 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:
php artisan vendor:publish --tag=api-response-translations1return [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
Add it to the api group, or globally to give every response the header:
1protected $middlewareGroups = [2 'api' => [3 \Pharaonic\Laravel\ApiResponse\Http\Middleware\AssignRequestId::class,4 'throttle:api',5 \Illuminate\Routing\Middleware\SubstituteBindings::class,6 ],7];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 sends. A Response also carries it in the body, unless its profile returns false from requestIdInBody():
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.
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.
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 8.1 or later), read when the response is built, so set them anywhere before you return.
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.
#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 |
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') | Adds a notification: success, info, warning or error. | 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() on a success, meta('pagination', ...) or shareMeta('pagination', ...), an unknown notification type, 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:
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:
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
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(): bool13 {14 return false;15 }16}1'profiles' => [2 'default' => Pharaonic\Laravel\ApiResponse\Profile::class,3 'mobile' => App\Http\Profiles\MobileProfile::class,4],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 with renderable() in your handler's register() (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.
#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 (8.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!
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?
Thanks, that helps us decide what to improve.
Something wrong or missing? Report it on GitHub .