true, ]; if ($data !== null) { $response['data'] = $data; } if ($message !== null) { $response['message'] = $message; } return response()->json($response, $code); } /** * 错误响应 * * @param string $error 错误代码 * @param string $message 错误消息 * @param mixed $errors 详细错误信息 * @param int $code HTTP状态码 * @return JsonResponse */ protected function error( string $error, string $message, mixed $errors = null, int $code = Response::HTTP_BAD_REQUEST ): JsonResponse { $response = [ 'success' => false, 'error' => $error, 'message' => $message, ]; if ($errors !== null) { $response['errors'] = $errors; } return response()->json($response, $code); } /** * 分页响应 * * @param array $items 分页数据 * @param array $meta 分页元数据 * @param string|null $message 成功消息 * @return JsonResponse */ protected function paginate(array $items, array $meta, ?string $message = null): JsonResponse { $response = [ 'success' => true, 'data' => $items, 'meta' => $meta, ]; if ($message !== null) { $response['message'] = $message; } return response()->json($response); } /** * 创建成功响应 * * @param mixed $data 创建的资源数据 * @param string|null $message 成功消息 * @return JsonResponse */ protected function created(mixed $data, ?string $message = null): JsonResponse { return $this->success($data, $message, Response::HTTP_CREATED); } /** * 无内容响应 * * @return JsonResponse */ protected function noContent(): JsonResponse { return response()->json(null, Response::HTTP_NO_CONTENT); } }