最轻量方式是用中间件在响应发出前统一包装API响应体,配合Trait主动构造响应,并通过自定义Header避免重复包装,同时改造异常处理器确保全链路格式一致。

用中间件统一包装 API 响应体
直接在响应发出前拦截并重写结构,是最轻量、侵入性最小的方式。Laravel 的 middleware 可以在 SendResponse 阶段之前介入,但更稳妥的做法是自定义一个响应中间件,在控制器返回后、框架序列化前处理。
常见错误是试图在中间件里修改 $response->content() 字符串,这会导致 JSON 解析失败或双层编码。正确做法是判断响应是否为 JsonResponse 实例,并用新实例替换。
- 新建中间件
app/Http/Middleware/ApiResponseFormat.php - 在
handle()中检查$response instanceof JsonResponse - 若匹配,提取原始数据:
$originalData = $response->getData(true) - 构造统一结构:
['code' => 200, 'message' => 'success', 'data' => $originalData] - 返回新的
JsonResponse,注意保留原状态码和响应头
public function handle($request, Closure $next)
{
$response = $next($request);
if ($response instanceof JsonResponse) {
$originalData = $response->getData(true);
$code = $response->getStatusCode();
$message = $code === 200 ? 'success' : 'error';
return response()->json([
'code' => $code,
'message' => $message,
'data' => $code === 200 ? $originalData : null,
'timestamp' => now()->timestamp,
], $code, $response->headers->allPreserveCase());
}
return $response;
}
用 Trait 封装常用响应方法
中间件解决“被动包装”,Trait 解决“主动构造”。把 success()、error()、fail() 这类方法抽成 ApiResponser Trait,让 Controller 复用,语义清晰且便于扩展。
容易踩的坑是直接在 Trait 里调用 response()->json() 后不加 return,导致后续逻辑继续执行;另一个问题是未区分 HTTP 状态码与业务 code,造成前端判断混乱。
- Trait 中每个方法必须以
return response()->json(...)结尾 - 显式分离:HTTP 状态码(如
422)走response()->json(..., 422),业务码(如'code' => 4001)放 data 结构内 - 支持可选参数:
$data、$message、$code(业务码)、$status(HTTP 状态) - 避免在
__construct()或初始化阶段加载 Trait,它只提供方法,不参与生命周期
trait ApiResponser
{
protected function success($data = null, $message = 'success', $code = 200, $status = 200)
{
return response()->json([
'code' => $code,
'message' => $message,
'data' => $data,
'timestamp' => now()->timestamp,
], $status);
}
protected function error($message = 'error', $code = 500, $status = 500)
{
return response()->json([
'code' => $code,
'message' => $message,
'data' => null,
'timestamp' => now()->timestamp,
], $status);
}
}
中间件与 Trait 如何配合使用
两者不是二选一,而是分层协作:Trait 用于明确意图的主动响应(如登录成功、参数校验失败),中间件用于兜底和标准化(如全局异常、第三方包返回的裸 JSON)。
典型冲突场景是控制器中用了 $this->success(),又被中间件二次包装——结果出现嵌套 data.data。根本原因是中间件无差别处理所有 JsonResponse,包括 Trait 构造的。
- 解决方案一:在 Trait 构造响应时打标记,比如设置自定义 header
X-Api-Formatted: true,中间件检测到就跳过 - 解决方案二:在中间件中排除已含
code/message键的 JSON 数据(需json_decode($response->content(), true)判断,有性能损耗) - 推荐方案一,更可控;header 不影响前端,又便于调试(curl -I 可见)
- 别忘了在中间件里补全 header:
$response->header('X-Api-Formatted', 'true')
兼容 Laravel 自带的异常响应
Laravel 默认的 Handler.php 对验证失败、模型未找到等会返回特定 JSON 格式,和你的统一格式不一致。不处理的话,404、422 响应就会“漏出”原始结构。
关键点在于:不要重写整个 render() 方法,而是在其中识别异常类型,再调用你封装好的响应方法。
- 在
app/Exceptions/Handler.php的render()中判断$request->is('api/*') - 对
ValidationException,提取$exception->errors()并传给$this->error() - 对
ModelNotFoundException,返回$this->error('record not found', 40401, 404) - 确保所有 API 异常最终都走到你定义的
code+message路径,而非 Laravel 默认的message+errors
最易忽略的是 500 错误——开发环境会返回调试页面,线上才 JSON,务必在 APP_DEBUG=false 下验证实际响应结构。










