anhht-0804/laravel-api-response 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

anhht-0804/laravel-api-response

Composer 安装命令:

composer require anhht-0804/laravel-api-response

包简介

A Laravel package for standardized API responses with automatic error handling and Japanese messages

README 文档

README

A Laravel package for standardized API responses with automatic error handling and Japanese messages.

Installation

composer require anhht-0804/laravel-api-response

Publishing Files for Customization

To customize constants and traits, publish them to your application:

php artisan api-response:publish

This will publish and automatically fix namespaces for:

  • app/Http/Constants/ApiResponseConstants.php - Customize messages and status codes
  • app/Http/Traits/ApiResponseTrait.php - Customize response methods
  • app/Http/Traits/GlobalErrorHandlerTrait.php - Customize error handling

Note: Publishing does NOT auto-bind anything. The package does not register the exception handler by default.

Optional: Bind the package Exception Handler

If you want to use the package exception handler, add a binding in your application provider:

// app/Providers/AppServiceProvider.php
use Illuminate\Contracts\Debug\ExceptionHandler;
use Anhht0804\LaravelApiResponse\Exceptions\ApiExceptionHandler;

public function register(): void
{
    $this->app->singleton(ExceptionHandler::class, ApiExceptionHandler::class);
}

Or create a dedicated provider and register it in config/app.php.

Usage

Automatic Error Handling

Exceptions are automatically handled for API routes (api/*) and JSON requests.

Manual Response Handling

use Anhht0804\LaravelApiResponse\Traits\ApiResponseTrait;

class ApiController extends Controller
{
    use ApiResponseTrait;
    
    public function index()
    {
        return $this->respondSuccess($data, 'Data retrieved successfully');
    }
    
    public function store()
    {
        return $this->respondCreated($data);
    }
}

Available Methods

  • respondSuccess($data, $message) - HTTP 200
  • respondCreated($data) - HTTP 201
  • respondBadRequest($message) - HTTP 400
  • respondUnauthorized($message) - HTTP 401
  • respondForbidden($message) - HTTP 403
  • respondNotFound($message) - HTTP 404
  • respondValidationError($errors) - HTTP 422
  • respondInternalError($message) - HTTP 500

Response Format

Success:

{
    "success": true,
    "data": {...},
    "message": "処理が完了しました"
}

Error:

{
    "success": false,
    "error": {
        "code": 404,
        "message": "リソースが見つかりません",
        "status": 404
    }
}

Validation Error:

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

Customization

Customizing Constants

After publishing, edit app/Http/Constants/ApiResponseConstants.php:

class ApiResponseConstants
{
    // Add your custom messages
    const SUCCESS_MESSAGES = [
        'GENERAL' => 'Operation completed successfully',
        'CREATED' => 'Resource created successfully',
        'CUSTOM_SUCCESS' => 'Your custom success message',
    ];
    
    const ERROR_MESSAGES = [
        'GENERAL' => 'An error occurred',
        'CUSTOM_ERROR' => 'Your custom error message',
    ];
    
    // Add custom status codes
    const HTTP_CUSTOM_SUCCESS = 200;
    const HTTP_CUSTOM_ERROR = 400;
}

Customizing Traits

Edit app/Http/Traits/ApiResponseTrait.php to add custom methods:

trait ApiResponseTrait
{
    // Override existing methods
    protected function respondSuccess($data = null, string $message = null): JsonResponse
    {
        $response = [
            'success' => true,
            'data' => $data ?? [],
            'message' => $message ?? 'Custom success message',
            'timestamp' => now(),
        ];
        
        return response()->json($response, 200);
    }
    
    // Add new custom methods
    protected function respondCustomSuccess($data = null): JsonResponse
    {
        return response()->json([
            'success' => true,
            'data' => $data,
            'message' => 'Custom success response',
            'custom_field' => 'custom_value'
        ]);
    }
}

Using Custom Files

In your controllers, use the published files:

use App\Http\Traits\ApiResponseTrait;
use App\Http\Constants\ApiResponseConstants;

class ApiController extends Controller
{
    use ApiResponseTrait;
    
    public function index()
    {
        return $this->respondSuccess($data, ApiResponseConstants::getSuccessMessage('CUSTOM_SUCCESS'));
    }
}

Requirements

  • PHP 8.0 or higher
  • Laravel 9.0 or higher

License

The MIT License (MIT). Please see License File for more information.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email your-email@example.com instead of using the issue tracker.

Credits

Changelog

Please see CHANGELOG for more information on what has changed recently.

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-10-03