kevupton / laravel-json-response
为 Laravel 提供简易的 Json 响应
v0.0.11
2018-12-09 02:13 UTC
Requires
- php: >=5.4
Requires (Dev)
- barryvdh/laravel-ide-helper: ^2.4
- laravel/laravel: 5.5.*
- laravel/lumen-framework: 5.5.*
README
Ethereal 包
以简单方式实现 API 格式化 Json 响应。
格式
{ "data": {...}, "errors": [], "success": true, "status_code": 200, "token": null }
设置
安装
composer require kevupton/laravel-json-response
将服务提供者添加到您的应用程序配置中
\Kevupton\LaravelJsonResponse\Providers\LaravelJsonResponseProvider::class,
将中间件添加到您的 app\Http\Kernel.php
或者
// Formats all responses in json. Catches errors listed in config and JsonResponseErrorExceptions Kevupton\LaravelJsonResponse\Middleware\OutputJsonResponse, // Extends the OutputJsonResponse to catch all errors, to keep the JSON output Kevupton\LaravelJsonResponse\Middleware\CatchAllExceptions,
配置
使用命令发布配置
php artisan vendor:publish
示例
返回数据的示例
用法
Route::get('test', function () { return ['hello' => true]; });
输出
{ "data": { "hello": true }, "errors": [], "success": true, "status_code": 200 }
直接操作 JSON 的示例
您也可以直接从这个方法设置数据和令牌。
用法
Route::get('test', function () { json_response()->error('This an example error message') ->setStatusCode(\Illuminate\Http\Response::HTTP_BAD_REQUEST); });
输出
{ "data": [], "errors": [ "This an example error message" ], "success": false, "status_code": 400 }
返回模型的示例
模型使用 snake_case 添加到数据中。
用法
Route::get('test', function () { return \App\Models\TestModel::find(2); });
输出
{ "data": { "test_model": { "id": 2 } }, "success": false, "status_code": 400 }
返回 Arrayable 的示例
具有 toArray 方法的 Arrayable 对象与数据合并。
用法
Route::get('test', function () { return \App\Models\TestModel::paginate(); });
输出
{ "data": { "current_page": 1, "data": [ { "id": 1 }, { "id": 2 }, ... ], "first_page_url": "http://url/api/test?page=1", "from": 1, "last_page": 3, "last_page_url": "http://url/api/test?page=3", "next_page_url": "http://url/api/test?page=2", "path": "http://url/api/test", "per_page": 10, "prev_page_url": null, "to": 10, "total": 24 }, "errors": [], "success": true, "status_code": 200 }
带有验证错误的示例
用法
Route::get('test', function () { throw new \Illuminate\Validation\ValidationException(\Validator::make([], ['test' => 'required'])); });
输出
{ "data": [], "errors": { "test": [ "The test field is required." ] }, "success": false, "status_code": 422 }
异常示例
注意:如果 APP_DEBUG=true
,则将显示堆栈跟踪
用法
Route::get('test', function () { throw new Exception('test'); });
输出
{ "data": [], "errors": [ "test message", { "file": "C:\\Users\\kevin\\Projects\\laravel\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\Route.php", "line": 172, "function": "runCallable", "class": "Illuminate\\Routing\\Route", "type": "->", "args": [] }, {...}, {...}, {...}, {...}, ... ], "success": false, "status_code": 500 }
异常处理
可以使用配置文件捕获异常
<?php use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Http\Response; use Illuminate\Validation\ValidationException; use Kevupton\LaravelJsonResponse\JsonResponse; return [ 'exceptions' => [ /** * Show model not found when receiving this error */ ModelNotFoundException::class => 'Model not found', // OR ModelNotFoundException::class => ['NOT_FOUND', 'Model not found'], // OR ModelNotFoundException::class => [ 'error' => 'Model not found', // these are functions on the JsonResponse, being dynamically invoked 'setStatusCode' => Response::HTTP_NOT_FOUND ], /** * Add all the errors from the validation and continue */ ValidationException::class => function (ValidationException $e, JsonResponse $json) { $json ->mergeErrors($e->errors()) ->setStatusCode(Response::HTTP_UNPROCESSABLE_ENTITY); } ] ];