shalvah / laravel-jsend
Laravel 辅助函数,轻松发送符合 JSend 标准的响应
2.4
2023-04-07 10:57 UTC
Requires
- php: >=7.2.5
- laravel/framework: >= 7.0
Requires (Dev)
- ext-json: *
- orchestra/testbench: ^5.0|^6.0|8.0
- phpunit/phpunit: ^8.0|^10.0
README
简单的辅助函数,用于为您的 Laravel 应用生成符合 JSend 标准的响应
JSend 规范规定了 Web 服务器返回的 JSON 响应应该如何格式化。JSend 特别适合 REST 风格的应用程序和 API。
安装
Laravel 7 及以上版本
composer require shalvah/laravel-jsend
Laravel 5.1 - 6.*
composer require shalvah/laravel-jsend:^1.0
使用方法
在控制器中
public function create(Request $request) { $userData = $request->input('data'); if (empty($userData['email'])) return jsend_fail(['email' => 'Email is required']); try { $user = User::create($userData): return jsend_success($user); } catch (Exception $e) { return jsend_error('Unable to create user: '.$e->getMessage()); } }
您还可以在 App\Exceptions\Handler
中添加 JsendExceptionFormatter
特性,以将未处理的异常和 Laravel 验证错误格式化为 JSend 格式
class Handler extends ExceptionHandler { use Shalvah\LaravelJsend\JsendExceptionFormatter; // ... }
可用的辅助函数
jsend_success
jsend_success
函数创建一个 JSend 成功 响应实例。
return jsend_success([ "id" => 2, "title" => "New life", "body" => "Trust me, this is great!" ]);
生成响应
{ "status": "success", "data": { "id": 2, "title": "New life", "body": "Trust me, this is great!" } }
您可以将 Eloquent 模型作为“数据”对象传递,而不是数组
$post = Post::find($id); return jsend_success($post);
jsend_fail
jsend_fail
函数创建一个 JSend 失败 响应实例。
return jsend_fail([ "title" => "title is required", "body" => "body must be 50 - 10000 words" ]);
生成响应
{ "status": "fail", "data": { "title": "title is required", "body": "body must be 50 - 10000 words" } }
jsend_error
jsend_error
函数创建一个 JSend 错误 响应实例。
return jsend_error("Unable to connect to database");
生成响应
{ "status": "error", "message":"Unable to connect to database" }
您还可以传递可选的 code
和 data
对象。
return jsend_error("Unable to connect to database", 'E0001', ['type' => 'database error']);
生成响应
{ "status": "error", "message":"Unable to connect to database", "code": "E001", "data": { "type": "database error" } }
注意:对于每个辅助函数,HTTP 状态码都会自动设置(分别为 200、400 和 500,分别对应
success
、fail
和error
),并且会设置Content-type: application/json
标头。如果您希望,可以指定 HTTP 状态码和额外的标头作为最后两个参数。
return jsend_success($post, 201, ["X-My-Header" => "header value"]); return jsend_fail(["location_id" => "Location not found"], 404); return jsend_error("Unable to connect to database", 'E0001', [], 503, ["X-My-Header" => "header value"]);
许可证
MIT