PHPackages                             talish/laravel-api-responses - 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. [HTTP &amp; Networking](/categories/http)
4. /
5. talish/laravel-api-responses

ActiveLibrary[HTTP &amp; Networking](/categories/http)

talish/laravel-api-responses
============================

A professional, expressive Laravel API response package. Replace verbose response()-&gt;json() calls with clean, consistent api()-&gt;success(), api()-&gt;error(), and more.

v1.0.0(1mo ago)01↓50%MITPHPPHP ^8.1

Since Jun 16Pushed 1mo agoCompare

[ Source](https://github.com/talishEG/laravel-api-responses)[ Packagist](https://packagist.org/packages/talish/laravel-api-responses)[ Docs](https://github.com/talish/laravel-api-responses)[ RSS](/packages/talish-laravel-api-responses/feed)WikiDiscussions master Synced 2w ago

READMEChangelogDependencies (5)Versions (2)Used By (0)

🚀 talish/laravel-api-responses
==============================

[](#-talishlaravel-api-responses)

[![Latest Version on Packagist](https://camo.githubusercontent.com/831215124f76a81a55164b70d07c8fcbfc9190258a447a9d1c462535d78963e6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f74616c6973682f6c61726176656c2d6170692d726573706f6e7365732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/talish/laravel-api-responses)[![Total Downloads](https://camo.githubusercontent.com/4f4c799e0d9c05e11521f98e49d583fcee7e48bb90316005b78af01740d1b18f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f74616c6973682f6c61726176656c2d6170692d726573706f6e7365732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/talish/laravel-api-responses)[![PHP Version Require](https://camo.githubusercontent.com/04001fd2c7320b4adf20abbec16296ab0f5d2cd728bb9a27413964057ec2e455/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f74616c6973682f6c61726176656c2d6170692d726573706f6e7365733f7374796c653d666c61742d737175617265)](https://packagist.org/packages/talish/laravel-api-responses)[![License](https://camo.githubusercontent.com/a861232608d0b717b8fb7bdef56ba9cc210246905cc332ead9cf36d6589165ca/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f74616c6973682f6c61726176656c2d6170692d726573706f6e7365732e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)

A professional, expressive Laravel API response package. Replace verbose `response()->json([...])` calls with clean, consistent, and self-documenting API responses.

**Before:**

```
return response()->json([
    'status'  => true,
    'message' => 'User created',
    'data'    => $user,
], 201);
```

**After:**

```
return api()->created($user, 'User created');
```

---

Requirements
------------

[](#requirements)

Package VersionLaravelPHP1.x10.x≥ 8.11.x11.x≥ 8.2---

Installation
------------

[](#installation)

```
composer require talish/laravel-api-responses
```

The package auto-discovers itself via Laravel's package discovery. No manual provider registration needed.

### Publish Config (optional)

[](#publish-config-optional)

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

This publishes `config/api-responses.php` where you can customise the response structure, JSON flags, and global headers.

---

Usage
-----

[](#usage)

### Global Helper `api()`

[](#global-helper-api)

The quickest way — available anywhere in your application:

```
// 200 OK
return api()->success($data);
return api()->success($data, 'Users fetched');

// 201 Created
return api()->created($user);
return api()->created($user, 'Account registered');

// 204 No Content
return api()->noContent();

// 400 Bad Request
return api()->badRequest('Invalid input');

// 401 Unauthorized
return api()->unauthorized();
return api()->unauthorized('Token has expired');

// 403 Forbidden
return api()->forbidden('You cannot access this resource');

// 404 Not Found
return api()->notFound();
return api()->notFound('Post not found');

// 422 Validation
return api()->validation($validator->errors());
return api()->validation($request->errors(), 'The form has errors');

// 429 Too Many Requests
return api()->tooManyRequests();

// 500 Server Error
return api()->error('Something went wrong');
return api()->error('Database failure', 500, ['detail' => '...']);

// 503 Service Unavailable
return api()->serviceUnavailable();

// Fully custom
return api()->custom(true, $data, 'All good', 200);
```

---

### Facade `ApiResponse::`

[](#facade-apiresponse)

```
use Talish\ApiResponses\Facades\ApiResponse;

return ApiResponse::success($data);
return ApiResponse::notFound('Item missing');
```

---

### `HasApiResponses` Trait (for Controllers)

[](#hasapiresponses-trait-for-controllers)

Add the trait to your base controller to call methods on `$this`:

```
use Talish\ApiResponses\Traits\HasApiResponses;

class Controller extends BaseController
{
    use HasApiResponses;
}

// In any child controller:
class UserController extends Controller
{
    public function index(): JsonResponse
    {
        $users = User::paginate(15);
        return $this->success($users, 'Users fetched');
    }

    public function store(StoreUserRequest $request): JsonResponse
    {
        $user = User::create($request->validated());
        return $this->created($user);
    }

    public function show(User $user): JsonResponse
    {
        return $this->success($user);
    }

    public function destroy(User $user): JsonResponse
    {
        $user->delete();
        return $this->noContent();
    }
}
```

---

Response JSON Structure
-----------------------

[](#response-json-structure)

Every response follows this consistent shape:

```
{
    "status": true,
    "status_code": 200,
    "message": "Success",
    "data": { ... }
}
```

Error responses add an optional `errors` key:

```
{
    "status": false,
    "status_code": 422,
    "message": "Validation failed",
    "data": null,
    "errors": {
        "email": ["The email field is required."]
    }
}
```

### Paginated Responses

[](#paginated-responses)

Pass a `LengthAwarePaginator` or `ResourceCollection` and pagination metadata is automatically included:

```
$users = User::paginate(15);
return api()->success($users);
```

```
{
    "status": true,
    "status_code": 200,
    "message": "Success",
    "data": [ ... ],
    "meta": {
        "current_page": 1,
        "per_page": 15,
        "total": 120,
        "last_page": 8,
        "from": 1,
        "to": 15,
        "path": "https://example.com/api/users"
    },
    "links": {
        "first": "https://example.com/api/users?page=1",
        "last": "https://example.com/api/users?page=8",
        "prev": null,
        "next": "https://example.com/api/users?page=2",
        "self": "https://example.com/api/users?page=1"
    }
}
```

---

Laravel API Resources
---------------------

[](#laravel-api-resources)

Works seamlessly with `JsonResource` and `ResourceCollection`:

```
return api()->success(new UserResource($user));
return api()->success(UserResource::collection($users));
```

---

Global Exception Handling
-------------------------

[](#global-exception-handling)

Register the included exception handler in `app/Exceptions/Handler.php` to automatically format all exceptions as API responses:

```
use Talish\ApiResponses\Exceptions\ApiExceptionHandler;

public function register(): void
{
    $this->renderable(function (Throwable $e, Request $request) {
        if ($request->expectsJson()) {
            return (new ApiExceptionHandler)->handle($e);
        }
    });
}
```

This automatically converts:

ExceptionResponse`ValidationException``422` with errors`AuthenticationException``401 Unauthorized``AuthorizationException``403 Forbidden``ModelNotFoundException``404 Not Found``NotFoundHttpException``404 Not Found``HttpException`Matching HTTP statusEverything else`500` (with trace in debug mode)---

Configuration
-------------

[](#configuration)

After publishing, edit `config/api-responses.php`:

```
return [
    // Keys and order in every response
    'structure' => [
        'status',
        'status_code',
        'message',
    ],

    // Strip null values from response payload
    'remove_null_values' => false,

    // json_encode() flags
    'json_options' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,

    // Global headers added to every response
    'headers' => [
        'X-API-Version' => '1.0',
    ],
];
```

---

Complete Controller Example
---------------------------

[](#complete-controller-example)

```
