felo-z / laravel-api-response
Laravel API response and exception handler with unified JSON contract
v2.0.0
2026-06-26 05:59 UTC
Requires
- php: ^8.4
- laravel/framework: ^13.0
Requires (Dev)
- laravel/pint: ^1.24
- mockery/mockery: ^1.6
- orchestra/testbench: ^11.0
- phpunit/phpunit: ^12.0
README
Laravel 13+ 统一 API 响应与异常处理扩展包。
要求
- PHP >= 8.4
- Laravel
^13.0
安装
composer require felo-z/laravel-api-response
发布配置(可选,包已内置默认配置):
php artisan vendor:publish --provider="FeloZ\LaravelApiResponse\ApiResponseServiceProvider"
快速使用
use FeloZ\LaravelApiResponse\Support\ApiCode; api_response()->ok(['id' => 1], 'ok'); api_response()->success(['id' => 1], 'success'); api_response()->message('创建成功', ['id' => 1], 201); api_response()->failed('参数错误', ApiCode::BIZ_FAILED, 400, ['field' => 'name']); api_response()->exception($throwable);
响应结构
成功响应示例:
{
"status": true,
"code": 0,
"message": "OK",
"data": {}
}
失败响应示例(有错误详情时):
{
"status": false,
"code": 1001,
"message": "邮箱格式不正确",
"data": null,
"error": {
"email": ["邮箱格式不正确"]
}
}
| 字段 | 说明 |
|---|---|
status |
业务状态(true / false),满足 status === (code === 0) |
code |
业务码:0 = 成功;1000–1999 = 包内置 ApiCode;其它整数 = 项目自定义 |
message |
提示文案 |
data |
成功数据(失败时为 null) |
error |
可选;生产环境会隐藏系统堆栈类诊断信息 |
HTTP 状态码在传输层独立存在,不写入 body code。204 / 205 无响应 body。
异常自动接管
安装后通过 ApiResponseServiceProvider 注册 render_using,对以下请求自动将未捕获异常转为统一 JSON:
expectsJson()为true- 路径匹配
render_api_paths(默认api/*)
业务代码只需 throw,无需手动 return api_response()->exception(...)。
文档
| 文档 | 说明 |
|---|---|
| api-response.md | 完整使用手册 |
| api-response-examples.md | Controller / 验证 / 异常接入示例 |
| api-response-project-extension.md | 项目自建业务码常量 |
| api-response-frontend-quick.md | 前端判定规则 |
| api-response-contract-template.md | 前后端协作约定模板 |
| api-response-production-template.md | 生产环境配置模板 |
| api-response-benchmark.md | pipes 性能压测 |
| api-response-upgrade.md | v1 → v2 升级说明 |
变更记录见 CHANGELOG.md。
开发
composer install
composer run test
composer run fix-style
License
MIT