PHPackages                             mitoop/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. mitoop/laravel-api-response

ActiveLibrary[API Development](/categories/api)

mitoop/laravel-api-response
===========================

v7.6.0(1mo ago)1236MITPHPPHP ^8.2

Since Aug 7Pushed 6mo ago1 watchersCompare

[ Source](https://github.com/mitoop/laravel-api-response)[ Packagist](https://packagist.org/packages/mitoop/laravel-api-response)[ RSS](/packages/mitoop-laravel-api-response/feed)WikiDiscussions main Synced 1mo ago

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

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

[](#laravel-api-response)

✨ 主要功能
------

[](#-主要功能)

🎯 提供统一且标准化的响应格式，同时支持普通分页与游标分页
🔧 支持自定义状态码与扩展字段
📦 灵活设置响应头（可添加签名、追踪 ID、版本号等）
🚀 无缝兼容 Laravel API 资源
🐛 已定制异常处理器，实现统一格式化输出

环境需求
----

[](#环境需求)

以下为最低环境要求：

- PHP &gt;= 8.2
- Laravel ^11.0｜^12.0

安装
--

[](#安装)

```
composer require mitoop/laravel-api-response
```

输出格式
----

[](#输出格式)

```
{
  "success": true,             // 请求是否成功。true 表示成功，false 表示失败。由系统自动判断，无需手动设置。
  "code": 0,                   // 状态码。默认值为 0（成功）、1（失败）、-1（登录失效），可通过 `setDefaults` 自定义。
  "message": "success",        // 提示信息
  "data": {},                  // 成功响应的主体内容
  "meta": {                    // 分页信息对象，仅在分页响应时返回
    "pagination": "page",      // 分页类型，可为 "page" 或 "cursor"
    "page": 1,                 // 当前页码（仅 page 分页）
    "page_size": 20,           // 每页条数
    "has_more": false,         // 是否有下一页
    "total": 100,              // 总条数（仅 paginate 方法有，simplePaginate 没有）
    "next_cursor": "..."       // 下一个游标（仅 cursor 分页）
  },
  "errors": {}                 // 错误详情对象，仅在请求失败时返回，类型可为 object 或 array
}
```

使用
--

[](#使用)

```
use Mitoop\Http\RespondsWithJson;

class Controller extends BaseController
{
    use RespondsWithJson;
}
```

#### 可用方法

[](#可用方法)

包含三个方法 `success`, `error`, `deny`, 分别对应成功, 失败, 登录失效三种情况

```
class Controller extends BaseController
{
    use RespondsWithJson;

    public function successEmpty()
    {
       return $this->success();
    }

    public function successWithData()
    {
       return $this->success(['Hello']);
    }

    public function successWithPagination()
    {
       return $this->success(User::active()->paginate());
    }

    public function errorDefault()
    {
       return $this->error();
    }

    public function errorCustomMessage()
    {
       return $this->error('自定义错误信息');
    }

    public function unauthorized()
    {
       return $this->deny('登录信息已失效, 请重新登陆!');
    }
}
```

自定义状态码以及扩展字段
------------

[](#自定义状态码以及扩展字段)

在 `AppServiceProvider@boot` 方法中添加如下代码

```
use Mitoop\Http\JsonResponderDefault;

app(JsonResponderDefault::class)->apply([
    'success' => 0,
    'error' => 1,
    'deny' => -1,
    'extra' => [
       'request_id' => app('request_id'),
    ],
]);
```

API 资源
------

[](#api-资源)

支持 API 资源, `只需要`改下继承关系, 其他不需要任何改变
Tips: 更改下系统默认的 `stub`, 每次直接生成好继承关系

#### 普通资源继承 `Mitoop\Http\Resources\Resource`

[](#普通资源继承-mitoophttpresourcesresource)

```
use Illuminate\Http\Request;
use Mitoop\Http\Resources\Resource;

class LoraResource extends Resource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
        ];
    }
}
```

#### 资源集合继承 `Mitoop\Http\Resources\ResourceCollection`

[](#资源集合继承-mitoophttpresourcesresourcecollection)

```
use Mitoop\Http\Resources\ResourceCollection;

class LoraCollection extends ResourceCollection
{

}
```

#### 和原来一样，直接返回资源对象，自动应用统一响应格式

[](#和原来一样直接返回资源对象自动应用统一响应格式)

```
class Controller extends BaseController
{
    public function show()
    {
       // 直接返回标准化的 API Resource
       return new LoraResource(Lora::find(1));
    }
}
```

异常
--

[](#异常)

已定制异常处理器，开发者只需少量配置即可实现统一格式化输出，同时支持完全自定义异常逻辑。

1. 在 `AppServiceProvider` 类中添加如下代码

```
    use Illuminate\Contracts\Debug\ExceptionHandler;
    use Mitoop\Http\Exceptions\Handler;

    public $singletons = [
        ExceptionHandler::class => Handler::class,
    ];
```

2. 在 `bootstrap/app.php` 中添加如下代码

```
use Illuminate\Foundation\Configuration\Exceptions;

->withExceptions(function (Exceptions $exceptions) {
    // 只需要根据需求配置异常映射
    // 其他异常由统一 Handler 接管，无需单独处理
    $exceptions->map(JWTException::class, fn ($e) => new AuthenticationException);
})
```

License
-------

[](#license)

MIT

###  Health Score

45

—

FairBetter than 93% of packages

Maintenance77

Regular maintenance activity

Popularity15

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity67

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 ~31 days

Recently: every ~44 days

Total

32

Last Release

46d ago

Major Versions

2.0.x-dev → 3.0.x-dev2024-04-16

v3.0.0 → v4.0.02025-01-25

v4.3.0 → v5.0.02025-05-02

v5.0.2 → v6.0.02025-08-01

v6.0.1 → v7.0.02025-09-13

PHP version history (2 changes)1.0.x-devPHP ^8.1

3.0.x-devPHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/1645a978f51dcbbc8e50a17bf7daaa12fd1b01a4b19784d0010325d78c9b53f8?d=identicon)[Mitoop](/maintainers/Mitoop)

---

Top Contributors

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

---

Tags

apiresponse

### Embed Badge

![Health badge](/badges/mitoop-laravel-api-response/health.svg)

```
[![Health](https://phpackages.com/badges/mitoop-laravel-api-response/health.svg)](https://phpackages.com/packages/mitoop-laravel-api-response)
```

###  Alternatives

[darkaonline/l5-swagger

OpenApi or Swagger integration to Laravel

2.9k34.0M112](/packages/darkaonline-l5-swagger)[echolabsdev/prism

A powerful Laravel package for integrating Large Language Models (LLMs) into your applications.

2.3k388.3k10](/packages/echolabsdev-prism)[sburina/laravel-whmcs-up

WHMCS API client and user provider for Laravel

271.3k](/packages/sburina-laravel-whmcs-up)

PHPackages © 2026

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