定制 json-box/laravel-api-response 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

json-box/laravel-api-response

Composer 安装命令:

composer require json-box/laravel-api-response

包简介

A simple and elegant API response formatter for Laravel applications

README 文档

README

Latest Version License

A Laravel package designed to enforce a consistent JSON API response structure across applications, improving maintainability and API clarity.

Table of Contents

Why use this package

  • Standardizes success, error and paginated JSON responses across your app.
  • Removes boilerplate response code from controllers.
  • Makes your API predictable and easier to document and consume.

Requirements

  • PHP >= 8.0
  • Laravel >= 9.x (adjust as necessary for your supported versions)

Installation

  1. Install via Composer
composer require sanjanarathnyke/laravel-json-response
  1. (Optional) Publish configuration and assets

If the package provides a config file, publish it with:

php artisan vendor:publish --provider="SanjanaRathnyke\LaravelJsonResponse\ServiceProvider" --tag="config"

Note: The package supports Laravel package auto-discovery. If auto-discovery is disabled, register the service provider manually in config/app.php:

'providers' => [
    // ...
    SanjanaRathnyke\LaravelJsonResponse\ServiceProvider::class,
];

Quick usage

The package exposes simple helpers/facade methods for returning standardized responses. Replace names below with the actual class/facade/helper names if they differ.

Controller — success response:

use Illuminate\Http\JsonResponse;
use SanjanaRathnyke\LaravelJsonResponse\Facades\JsonResponse;

class UserController extends Controller
{
    public function show(User $user): JsonResponse
    {
        return JsonResponse::success($user, 'User retrieved successfully');
    }
}

Controller — error response:

return JsonResponse::error('Resource not found', 404);

Controller — validation error:

return JsonResponse::errorValidation($validator->errors(), 'Validation failed', 422);

Response structure

Success response example:

{
  "success": true,
  "data": { /* resource data */ },
  "message": "Operation successful",
  "meta": {}
}

Error response example:

{
  "success": false,
  "error": {
    "code": 422,
    "message": "Validation failed",
    "errors": {
      "email": ["The email field is required."]
    }
  }
}

Paginated response example:

{
  "success": true,
  "data": [ /* items */ ],
  "message": "List of items",
  "meta": {
    "pagination": {
      "total": 100,
      "count": 10,
      "per_page": 10,
      "current_page": 1,
      "total_pages": 10
    }
  }
}

Configuration

When published, the configuration (example: config/jsonresponse.php) may include options such as:

return [
    'keys' => [
        'success' => 'success',
        'data' => 'data',
        'message' => 'message',
        'error' => 'error',
        'meta' => 'meta',
    ],

    'defaults' => [
        'success_message' => 'Operation successful.',
        'error_message' => 'An error occurred.',
        'success_code' => 200,
        'error_code' => 400,
    ],

    'include_debug' => env('APP_DEBUG', false),
];

Customization & extension

  • Transformers: Use Laravel API Resources or pass transformer callbacks to shape your data.
  • Global wrapping: Register middleware to wrap all responses automatically.
  • Exception handling: In app/Exceptions/Handler.php you can call the package's error helper in render() or register() to ensure all exceptions return the standardized JSON shape.

Examples

Return a paginated collection using a Resource:

$users = UserResource::collection(User::paginate(15));

return JsonResponse::success(
    $users,
    'Users list',
    [
        'pagination' => [
            'total' => $users->resource->total(),
            'count' => $users->resource->count(),
            'per_page' => $users->resource->perPage(),
            'current_page' => $users->resource->currentPage(),
            'total_pages' => $users->resource->lastPage(),
        ]
    ]
);

Return a custom error payload:

return JsonResponse::error(
    'Payment required to access this endpoint',
    402,
    ['policy' => 'upgrade_account']
);

Testing

Run the package test suite:

composer install
vendor/bin/phpunit
# or if the project uses Pest
vendor/bin/pest

Ensure test environment variables are configured (.env.testing or phpunit.xml) for database and other services used in tests.

Contributing

Contributions are welcome — thank you!

  • Fork the repository
  • Create a feature branch: git checkout -b feature/your-feature
  • Write tests for your change
  • Adhere to PSR-12 coding style
  • Open a pull request describing your changes

Please open issues for bug reports or feature requests.

License

This project is open source and available under the MIT License. See the LICENSE file for details.

Credits

Notes / Next steps

  • If any class names, facade names, helper functions, publish tags, or the configuration file differ from the examples above, tell me the exact names and I will update this README to match the code in your repository.
  • If you want, I can create a PR that replaces the existing README with this version — tell me and provide any additional clarifications (supported Laravel/PHP versions, exact usage examples) and I will prepare the PR.

json-box/laravel-api-response 适用场景与选型建议

json-box/laravel-api-response 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 3, 最近一次更新时间为 2026 年 01 月 05 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「json」 「api」 「response」 「formatter」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 json-box/laravel-api-response 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 json-box/laravel-api-response 我们能提供哪些服务?
定制开发 / 二次开发

基于 json-box/laravel-api-response 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 3
  • 点击次数: 35
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 3
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2026-01-05