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

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

softinvest/http-response
========================

HttpResponse Wrapper

v1.0.8(1mo ago)03.2k1MITPHPPHP &gt;=8.1

Since Nov 13Pushed 1mo ago1 watchersCompare

[ Source](https://github.com/softinvest/http-response)[ Packagist](https://packagist.org/packages/softinvest/http-response)[ RSS](/packages/softinvest-http-response/feed)WikiDiscussions main Synced today

READMEChangelog (7)DependenciesVersions (8)Used By (1)

HTTP Responses Library
======================

[](#http-responses-library)

[![PHP Version](https://camo.githubusercontent.com/d332c02139e0abd65c7c603532e2abdeca3fa33577802313a9d1f5d42633971b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e302d3838393242462e7376673f7374796c653d666c61742d737175617265)](https://php.net)[![Laravel Version](https://camo.githubusercontent.com/2a5adffb128fea0dde271595d144bd9bc0d19f4b1673c6c02b6f72dd0956cf1a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c61726176656c2d3825324639253246313025324631312d4646324432302e7376673f7374796c653d666c61742d737175617265)](https://laravel.com)[![License](https://camo.githubusercontent.com/942e017bf0672002dd32a857c95d66f28c5900ab541838c6c664442516309c8a/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Packagist Version](https://camo.githubusercontent.com/3dd92aa87a6db6ec1468780ff00e04f7f22301ee4c1fb8a848b235789bbe438d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f736f6674696e766573742f687474702d726573706f6e73652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/softinvest/http-response)![Build Status](https://camo.githubusercontent.com/07a93c6c3a828e1e929e2a173231acc84705e6f7a486f6d8d0f4103f204a79d1/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6275696c642d70617373696e672d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)

A flexible, Laravel‑friendly HTTP response library that standardizes API responses, exception handling, and output formats (plain text, JSON).
Provides a base controller with helper methods for consistent error handling, resource transformation, and IP detection.

Features
--------

[](#features)

- **Unified response structure** via `AbstractResponse` and concrete classes (`ResponseSuccess`, `ResponseFailure`, `ResponseCreated`, `ResponseOk`).
- **JSON &amp; plain text** output formats.
- **Exception handling** with optional stack trace inclusion.
- **Laravel resource support** – single resources and collections.
- **CloudFlare compatible** – retrieves real client IP from `HTTP_CF_CONNECTING_IP`.
- **Extensible** – create your own response types by extending `AbstractResponse`.

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

[](#requirements)

- PHP 8.0 or higher
- Laravel 8+ (or any Illuminate HTTP component)

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

[](#installation)

```
composer require softinvest/http-response
```

Basic Usage
-----------

[](#basic-usage)

### 1. Extend the base controller

[](#1-extend-the-base-controller)

Make your controllers extend `HttpResponseController`:

```
use SoftInvest\Http\Controllers\HttpResponseController;

class UserController extends HttpResponseController
{
    // Your methods...
}
```

### 2. Simple success response (plain text or JSON)

[](#2-simple-success-response-plain-text-or-json)

```
public function index()
{
    $data = "Hello, world!";

    // Plain text response
    return $this->renderSuccessResponse($data, self::FORMAT_PLAIN);

    // JSON response
    return $this->renderSuccessResponse($data, self::FORMAT_JSON);
}
```

### 3. Using the `response` helper (recommended)

[](#3-using-the-response-helper-recommended)

Wrap your business logic in a callback – any exception will be automatically converted into a `ResponseFailure` JSON response.

```
public function show($id)
{
    return $this->response(function () use ($id) {
        return User::findOrFail($id);
    });
}
```

### 4. Using Laravel Resources

[](#4-using-laravel-resources)

```
use App\Http\Resources\UserResource;

public function show($id)
{
    return $this->responseWithResource(
        UserResource::class,
        function () use ($id) {
            return User::findOrFail($id);
        }
    );
}

public function index()
{
    return $this->responseWithResourceCollection(
        UserResource::class,
        function () {
            return User::all();
        }
    );
}
```

### 5. Custom success/failure classes

[](#5-custom-successfailure-classes)

You can inject different response classes (must extend `AbstractResponse`):

```
$this->response(
    callback: fn() => $someData,
    successResponseCassName: CustomSuccess::class,
    failureResponseCassName: CustomFailure::class
);
```

### 6. Enabling stack traces in error responses

[](#6-enabling-stack-traces-in-error-responses)

Set `$hasTrace = true` in your controller to include the exception trace in failure responses.

```
class MyController extends HttpResponseController
{
    protected bool $hasTrace = true;
}
```

### 7. Getting client IP (with CloudFlare support)

[](#7-getting-client-ip-with-cloudflare-support)

```
$ip = $this->getUserIP(); // Automatically checks HTTP_CF_CONNECTING_IP first
```

Response Classes
----------------

[](#response-classes)

ClassDescriptionDefault HTTP status`ResponseSuccess`Standard success response with `success: true`200 OK`ResponseCreated`Success response for resource creation201 Created`ResponseOk`Minimal JSON `{"status":"ok"}`200 OK`ResponseFailure`Error response with message and optional trace400 Bad Request`ResponseHttpStatusWorkaround`Same as `ResponseFailure` but `setStatus()` does nothing (legacy compatibility)400 Bad RequestAll responses extend `AbstractResponse` and provide:

- `asJSON()` – returns `Illuminate\Http\JsonResponse`
- `asPlainText()` – returns `Illuminate\Http\Response` (plain text)
- `setData()`, `setStatus()`, `getData()`, etc.

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

[](#json-response-structure)

The `TAsJsonStandard` trait (used in `ResponseSuccess` and `ResponseFailure`) produces the following JSON shape:

```
{
    "success": true,
    "data": { ... },
    "error": null,
    "status": 200
}
```

For failures:

```
{
    "success": false,
    "data": null,
    "error": "Something went wrong",
    "status": 400
}
```

*You can override the trait or implement your own `asJSON()` method in custom responses.*

Exception Handling in `response()` methods
------------------------------------------

[](#exception-handling-in-response-methods)

When an exception is caught:

- Message (and optional stack trace) is placed into the `error` field.
- HTTP status code is taken from the exception’s `getCode()` (if between 200–999), otherwise defaults to `400`.
- The response is always returned as JSON.

Extending
---------

[](#extending)

### Create a custom response class

[](#create-a-custom-response-class)

```
use SoftInvest\Http\Responses\AbstractResponse;
use Illuminate\Http\JsonResponse;

class MyCustomResponse extends AbstractResponse
{
    protected ?bool $success = true;
    protected $status = 200;

    public function asJSON(): JsonResponse
    {
        return new JsonResponse([
            'custom' => $this->data,
            'version' => '1.0'
        ], $this->status);
    }
}
```

Then use it with `$this->response(..., successResponseCassName: MyCustomResponse::class)`.

Advanced: Direct usage without controller
-----------------------------------------

[](#advanced-direct-usage-without-controller)

You can instantiate responses directly:

```
use SoftInvest\Http\Responses\ResponseSuccess;
use SoftInvest\Http\Responses\ResponseFailure;

$success = (new ResponseSuccess())->setData(['id' => 1])->asJSON();
$failure = (new ResponseFailure('Not found', 404))->asJSON();
```

License
-------

[](#license)

GPLv2

###  Health Score

48

—

FairBetter than 93% of packages

Maintenance92

Actively maintained with recent releases

Popularity19

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~215 days

Recently: every ~270 days

Total

7

Last Release

38d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/60221974?v=4)[softinvest](/maintainers/softinvest)[@softinvest](https://github.com/softinvest)

---

Top Contributors

[![bugfix666](https://avatars.githubusercontent.com/u/151177991?v=4)](https://github.com/bugfix666 "bugfix666 (4 commits)")

---

Tags

http response wrapper

### Embed Badge

![Health badge](/badges/softinvest-http-response/health.svg)

```
[![Health](https://phpackages.com/badges/softinvest-http-response/health.svg)](https://phpackages.com/packages/softinvest-http-response)
```

###  Alternatives

[php-http/cache-plugin

PSR-6 Cache plugin for HTTPlug

25126.1M82](/packages/php-http-cache-plugin)[illuminate/http

The Illuminate Http package.

11937.9M6.9k](/packages/illuminate-http)[rdkafka/rdkafka

A PHP extension for Kafka

2.2k24.3k1](/packages/rdkafka-rdkafka)[httpsoft/http-message

Strict and fast implementation of PSR-7 and PSR-17

87965.9k114](/packages/httpsoft-http-message)[mezzio/mezzio-router

Router subcomponent for Mezzio

265.4M90](/packages/mezzio-mezzio-router)[serpapi/google-search-results-php

Get Google, Bing, Baidu, Ebay, Yahoo, Yandex, Home depot, Naver, Apple, Duckduckgo, Youtube search results via SerpApi.com

69127.2k](/packages/serpapi-google-search-results-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
