PHPackages                             php-dev-umesh/laravel-api-response - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. php-dev-umesh/laravel-api-response

ActiveLibrary[API Development](/categories/api)

php-dev-umesh/laravel-api-response
==================================

Comprehensive API response builder for Laravel with success, error, pagination, streaming, download responses, auto-translation, and exception handling.

00PHPCI passing

Since Jul 1Pushed todayCompare

[ Source](https://github.com/php-dev-umesh/laravel-api-response)[ Packagist](https://packagist.org/packages/php-dev-umesh/laravel-api-response)[ RSS](/packages/php-dev-umesh-laravel-api-response/feed)WikiDiscussions main Synced today

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel API Response Builder
============================

[](#laravel-api-response-builder)

[![Version](https://camo.githubusercontent.com/a89e7b105ed96f5df779c957a407096e8ba56f262655c3fdbcfec50cf634dd47/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f76657273696f6e2d312e302e312d626c75652e737667)](https://github.com/php-dev-umesh/laravel-api-response)[![PHP](https://camo.githubusercontent.com/aa05dec3dc522557f6fefc7a1a4f7b0bb6bd3641be0786641d4037f42d940c0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d382e312b2d2532333737374242342e737667)](https://php.net)[![Laravel](https://camo.githubusercontent.com/f3a61bcb8ecdcac7a4f44b579748e6fbc2f1640717148b85b13764e530830171/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c61726176656c2d31302537433131253743313225374331332d7265642e737667)](https://laravel.com)[![License](https://camo.githubusercontent.com/8bb50fd2278f18fc326bf71f6e88ca8f884f72f179d3e555e20ed30157190d0d/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d677265656e2e737667)](LICENSE)

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.

**Supports Laravel 10, 11, 12, and 13.**

---

Features
--------

[](#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 `UserResource` and 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** — `ApiFormRequest` returns 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
------------

[](#installation)

```
composer require php-dev-umesh/laravel-api-response
```

Publish the config file (optional — defaults work out of the box):

```
php artisan vendor:publish --tag=api-response-config
```

This creates `config/api-response.php`.

---

Quick Start
-----------

[](#quick-start)

```
use PhpDevUmesh\LaravelApiResponse\Facades\ApiResponse;

// In any controller or route:
ApiResponse::success($user, 'user.found');
// → {success: true, status: 200, message: "User found", data: {...}}

ApiResponse::error('user.not_found', 404);
// → {success: false, status: 404, message: "User not found", data: null}
```

Or use the trait in your controllers:

```
use PhpDevUmesh\LaravelApiResponse\Traits\ApiResponseTrait;

class UserController extends Controller
{
    use ApiResponseTrait;

    public function index()
    {
        return $this->paginated(User::paginate(), 'users.loaded');
    }

    public function store(StoreUserRequest $request)
    {
        return $this->created(User::create(...), 'user.created');
    }
}
```

---

Response Format
---------------

[](#response-format)

Default structure:

```
{
  "success": true,
  "status": 200,
  "message": "User found",
  "data": { ... }
}
```

All keys are configurable in `config/api-response.php`:

```
'format' => [
    'success_key' => 'success',
    'status_key'  => 'status',
    'message_key' => 'message',
    'data_key'    => 'data',
],
```

---

Full API Reference
------------------

[](#full-api-reference)

### Success Responses

[](#success-responses)

MethodDescriptionDefault Status`success($data, $message, $replace, $statusCode)`Generic success200`created($data, $message, $replace)`Resource created201`ok($data)`Success without message200`noContent()`Success with no content204`message($message, $replace)`Success with only message200```
ApiResponse::success($user, 'user.found');
ApiResponse::success($user, 'user.found', ['name' => $user->name]);
ApiResponse::created($user, 'user.created');
ApiResponse::ok($users);
ApiResponse::noContent();
ApiResponse::message('operation.completed');
```

### Error Responses

[](#error-responses)

MethodDescriptionDefault Status`error($message, $statusCode, $data)`Generic error400`validationError($errors, $message)`Validation error422```
ApiResponse::error('user.not_found', 404);
ApiResponse::error('Unauthorized', 401);
ApiResponse::validationError($validator->errors());
```

### Pagination

[](#pagination)

MethodDescription`paginated($paginator, $message, $replace)`Paginated collection`paginatedResource($resourceClass, $paginator, $message, $replace)`Paginated with API Resources```
ApiResponse::paginated(User::paginate(), 'users.loaded');

// Standard format (config 'standard'):
// {success, status, message, data: [...], meta: {current_page, last_page, per_page, total, has_more, ...}}

// Flat format (config 'flat'):
// {success, status, message, data: [...], total_page: 10, next_page: "..."}
```

### API Resources

[](#api-resources)

MethodDescription`resource($class, $model, $message)`Single resource`collection($class, $models, $message)`Resource collection`paginatedResource($class, $paginator, $message, $replace)`Paginated resources```
ApiResponse::resource(UserResource::class, $user);
ApiResponse::collection(UserResource::class, User::all());
ApiResponse::paginatedResource(UserResource::class, User::paginate(), 'users.loaded');
```

### Streaming

[](#streaming)

MethodDescriptionContent-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````
// Stream large dataset line-by-line (no memory spike)
ApiResponse::stream(function () {
    foreach (User::cursor() as $user) {
        echo json_encode(['id' => $user->id, 'name' => $user->name]) . "\n";
    }
}, 'exporting.users');

// Server-Sent Events for real-time progress
ApiResponse::sse(function ($emit) {
    foreach ($process as $step) {
        $emit(['progress' => $step / $total], 'progress');
        usleep(500000);
    }
    $emit(['message' => 'Complete'], 'complete');
});

// Lazy collection stream
ApiResponse::lazy(User::cursor(), 'exporting.users');
```

### Downloads

[](#downloads)

MethodDescription`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```
ApiResponse::download(storage_path('app/report.pdf'), 'report.pdf');
ApiResponse::file(storage_path('app/invoice.pdf'));
ApiResponse::streamDownload(function () {
    $handle = fopen('php://output', 'w');
    fputcsv($handle, ['Name', 'Email']);
    foreach (User::cursor() as $user) {
        fputcsv($handle, [$user->name, $user->email]);
    }
    fclose($handle);
}, 'users.csv');

ApiResponse::csv(
    headers: ['Name', 'Email', 'Score'],
    rows: User::cursor()->map(fn($u) => [$u->name, $u->email, $u->score]),
    filename: 'scores.csv'
);

ApiResponse::downloadFromDisk('s3', 'exports/report.pdf', 'report.pdf');
```

---

Auto-Translation
----------------

[](#auto-translation)

When `auto_translate` is `true` (default), every message string is automatically run through Laravel's `__()` helper.

```
// config/api-response.php
'auto_translate' => true,
'lang_prefix'    => 'message.',
'lang_fallback'  => true,

// In your code — just pass the key:
ApiResponse::success($user, 'user.found');
// Automatically resolves to: __("message.user.found")
// If translation file has: "user.found" => "User found successfully"
// Response: { "message": "User found successfully" }

// With dynamic replacements:
ApiResponse::success($user, 'welcome_user', ['name' => 'Umesh']);
// Resolves to: __("message.welcome_user", ['name' => 'Umesh'])
// If lang file has: "welcome_user" => "Welcome, :name!"
// Response: { "message": "Welcome, Umesh!" }

// Fallback behavior:
// if "message.user.found" doesn't exist in lang files AND lang_fallback = true
// → uses "user.found" as the raw message

// Disable auto-translate:
'auto_translate' => false,
// Now strings pass through as-is: "user.found" → "user.found"
```

You can also use the `api_trans()` helper anywhere:

```
$text = api_trans('user.found', ['name' => 'Umesh']);
```

Global replacement defaults can be set in config:

```
'lang_replace' => ['app_name' => 'MyApp'],
// Merged with any per-call replacements
```

---

Exception Handling
------------------

[](#exception-handling)

### Option A — Laravel 10: Handler Trait

[](#option-a--laravel-10-handler-trait)

Add the trait to `app/Exceptions/Handler.php`:

```
