Download the PHP package php-dev-umesh/laravel-api-response without Composer
On this page you can find all versions of the php package php-dev-umesh/laravel-api-response. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download php-dev-umesh/laravel-api-response
More information about php-dev-umesh/laravel-api-response
Files in php-dev-umesh/laravel-api-response
Package laravel-api-response
Short Description Comprehensive API response builder for Laravel with success, error, pagination, streaming, download responses, auto-translation, and exception handling.
License MIT
Informations about the package laravel-api-response
Laravel API Response Builder — Consistent JSON Responses for Laravel
A comprehensive, fluent API response builder for Laravel with 30+ methods covering success, error, pagination, API resources, streaming (NDJSON/SSE), file downloads, auto-translation, and exception handling — all in one consistent format. Eliminate duplicated JSON response code across your Laravel REST API. Includes auto-translation, exception handling, ApiFormRequest, and auto-wrap middleware for retrofitting existing APIs.
Supports Laravel 10, 11, 12, and 13. Works with PHP 8.1+.
Features
- Fluent response builder —
ApiResponse::success(),error(),created(),noContent(), etc. - Auto-translate — every message auto-resolves via
__("message.$key")with configurable prefix and fallback - Pagination — standard meta format or flat format (matching
{total_page, next_page}style) - API Resources — wrap
UserResourceand collections seamlessly - Streaming — NDJSON streams, Server-Sent Events (SSE), lazy collections
- Downloads — file download, inline preview, streaming CSV generation, storage disk downloads
- Exception handling — single trait or one-liner registration for common API exceptions
- Form Request —
ApiFormRequestreturns API-consistent validation errors - Auto-wrap middleware — retrofit existing
response()->json()code - Configurable — custom response keys (success/status/message/data), status codes, translation behavior
- Zero duplication — no more copy-pasting helper classes between projects
Installation
From Packagist (recommended)
From GitHub Packages
Add the GitHub Packages Composer registry and require the package:
Then authenticate with a GitHub Personal Access Token (classic PAT with read:packages scope):
Now run:
Publish Config (Optional)
This creates config/api-response.php (defaults work out of the box).
Quick Start
Or use the trait in your controllers:
Response Format
Default structure:
All keys are configurable in config/api-response.php:
Full API Reference
Success Responses
| Method | Description | Default Status |
|---|---|---|
success($data, $message, $replace, $statusCode) |
Generic success | 200 |
created($data, $message, $replace) |
Resource created | 201 |
ok($data) |
Success without message | 200 |
noContent() |
Success with no content | 204 |
message($message, $replace) |
Success with only message | 200 |
Error Responses
| Method | Description | Default Status |
|---|---|---|
error($message, $statusCode, $data) |
Generic error | 400 |
validationError($errors, $message) |
Validation error | 422 |
Pagination
| Method | Description |
|---|---|
paginated($paginator, $message, $replace) |
Paginated collection |
paginatedResource($resourceClass, $paginator, $message, $replace) |
Paginated with API Resources |
API Resources
| Method | Description |
|---|---|
resource($class, $model, $message) |
Single resource |
collection($class, $models, $message) |
Resource collection |
paginatedResource($class, $paginator, $message, $replace) |
Paginated resources |
Streaming
| Method | Description | Content-Type |
|---|---|---|
stream($callback, $message, $replace) |
NDJSON stream with header | application/x-ndjson |
streamJson($data) |
Single JSON stream | application/json |
sse($callback) |
Server-Sent Events | text/event-stream |
lazy($cursor, $message, $replace) |
Lazy collection stream | application/x-ndjson |
Downloads
| Method | Description |
|---|---|
download($path, $name) |
Force file download |
file($path) |
Inline file preview |
streamDownload($callback, $name) |
Generate file on the fly |
csv($headers, $rows, $filename) |
Stream CSV download |
downloadFromDisk($disk, $path, $name) |
Download from storage disk |
Auto-Translation
When auto_translate is true (default), every message string is automatically run through Laravel's __() helper.
You can also use the api_trans() helper anywhere:
Global replacement defaults can be set in config:
Exception Handling
Option A — Laravel 10: Handler Trait
Add the trait to app/Exceptions/Handler.php:
Option B — Laravel 11/12/13: Bootstrap Registration
In bootstrap/app.php:
What gets handled automatically:
| Exception | HTTP Status |
|---|---|
AuthenticationException |
401 |
ModelNotFoundException |
404 |
ValidationException |
422 (with errors) |
NotFoundHttpException |
404 |
MethodNotAllowedHttpException |
405 |
ThrottleRequestsException |
429 |
ApiException |
Custom (default 400) |
Any other Throwable |
500 (with debug trace if APP_DEBUG=true) |
Throwable ApiException
Throw from anywhere in your application:
ApiFormRequest (Validation)
Replace extends FormRequest with extends ApiFormRequest:
On validation failure, automatically returns:
Auto-Wrap Middleware
Retrofit existing controllers that use raw response()->json() without modifying them:
The middleware skips:
- Non-JSON responses
- Responses already in the package format (by detecting the
success/statuskeys) - Already-wrapped responses (detected via
X-Api-Response-Wrappedheader)
Configuration Reference
config/api-response.php
Access any config value:
Migration from Your Current Code
If you're using a custom Helper class similar to the one this package replaces:
| Current Code | Replace With |
|---|---|
Helper::SuccessReturn($data, 'key') |
ApiResponse::success($data, 'key') |
Helper::FalseReturn($data, 'key') |
ApiResponse::error('key') |
Helper::EmptyReturn('key') |
ApiResponse::message('key') or ApiResponse::error('key', 404) |
Helper::StatusReturn($data, 'key', [], [], 201) |
ApiResponse::created($data, 'key') |
Helper::SuccessReturnPagination($data, $total, $next, 'key') |
ApiResponse::paginated($paginator, 'key') |
Helper::UpdateObjectIfKeyExist($obj, $req, $keys) |
Use $obj->fill($req->only($keys)) or $obj->update($req->only($keys)) |
throw new PublicException($msg, $code) |
throw ApiException::make($msg, $code) |
PublicException::Validator($data, $rules) |
Use ApiFormRequest instead |
PublicException::NotSave($state) |
ApiException::throwIfNotSave($state) |
PublicException::Empty($obj) |
ApiException::throwIfEmpty($obj) |
PublicException::SaveAndCommit($obj) |
DB::transaction(fn => ApiException::throwIfNotSave($obj->save())) |
__("message." . $key) boilerplate repeated everywhere |
Set auto_translate: true — package handles it centrally |
Testing (using Orchestra Testbench)
The package is tested against Laravel 10, 11, 12, and 13 using Orchestra Testbench.
Example test:
Requirements
- PHP 8.1 or higher
- Laravel 10, 11, 12, or 13
Changelog
See CHANGELOG for recent changes.
Contributing
See CONTRIBUTING for details.
Community & Outreach
- Laravel News — Follow for Laravel ecosystem updates
- r/laravel — Discuss Laravel packages and development
- Laravel.io Forum — Community discussions
- DEV.to — Laravel tutorials and package showcases
- X/Twitter — Tag @laravelphp with your API projects
If you find this package useful, please star the repo on GitHub — it helps others discover it!
License
This package is open-source software licensed under the MIT license.