djurovicigoor/larajsonresponse

Laravel API 响应包装器,用于返回 JSON 响应。

v1.0.4 2020-09-14 14:56 UTC

This package is auto-updated.

Last update: 2024-09-10 21:21:25 UTC


README

Latest Version on Packagist Total Downloads License: MIT Scrutinizer code quality (GitHub/Bitbucket) Scrutinizer build (GitHub/Bitbucket)

Laravel API 响应包装器,用于返回 JSON 响应。

安装

通过 Composer

$ composer require djurovicigoor/larajsonresponse

使用方法

基本方法是 laraResponse();

    return laraResponse();

此方法的 JSON 响应将是

{
    "code": 200,
    "message": null,
    "data": null,
    "error": null
}

如果您想返回包含数据和状态码 200 的成功 JSON 响应,您必须使用 laraResponse($message , $data)->success()

    $data = ['name' => 'John Doe', 'location' => 'unknown' , 'age' => 24];
	
    return laraResponse("My message." , $data)->success();

此方法的 JSON 响应将是

{
    "code": 200,
    "message": "My message.",
    "data": {
        "name": "John Doe",
        "location": "unknown",
        "age": 24
    },
    "error": null
}

如果您想返回包含消息、ERROR 和状态码 400 的错误 JSON 响应,您必须使用 laraResponse($message , NULL , $error)->error()

    return laraResponse('My message.' , NULL , "TYPE_OF_ERROR")->error();

此方法的 JSON 响应将是

{
    "code": 400,
    "message": "My message.",
    "data": null,
    "error": "TYPE_OF_ERROR"
}

如果您想返回包含 401 状态码的无权访问 JSON 响应,您必须使用 laraResponse($message)->unAuthorized()

    return laraResponse('This action is unauthorized.')->unAuthorized();

此方法的 JSON 响应将是

{
    "code": 401,
    "message": "This action is unauthorized.",
    "data": null,
    "error": null
}

如果您想返回包含 403 状态码的禁止访问 JSON 响应,您必须使用 laraResponse($message)->forbidden()

    return laraResponse('Forbidden!')->forbidden();

此方法的 JSON 响应将是

{
    "code": 403,
    "message": "Forbidden!",
    "data": null,
    "error": null
}

如果您想返回包含 404 状态码的未找到 JSON 响应,您必须使用 laraResponse($message)->notFound()

    return laraResponse('Not Found!')->notFound();

此方法的 JSON 响应将是

{
    "code": 404,
    "message": "Not Found!",
    "data": null,
    "error": null
}

最后,您可以使用 laraResponse($message)->customCode($yourCustomCode) 返回包含您自定义代码的 JSON 响应;

return laraResponse('My custom status code!')->customCode($yourCustomCode);

此方法的 JSON 响应将是

{
    "code": $yourCustomCode,
    "message": "My custom status code!",
    "data": null,
    "error": null
}

变更日志

请参阅变更日志以获取有关最近更改的更多信息。

贡献

请参阅contributing.md以获取详细信息和一个待办事项列表。

安全性

如果您发现任何与安全性相关的问题,请通过电子邮件djurovic.igoor@gmail.com而不是使用问题跟踪器。

捐赠

如果您发现这个项目很有帮助,或者您从源代码中学到了一些东西,并且想表示感谢

鸣谢

许可协议

MIT. 请参阅许可文件以获取更多信息。