项目作者: imdhemy

项目描述 :
Laravel JSON response trait.
高级语言: PHP
项目地址: git://github.com/imdhemy/jsonable.git
创建时间: 2019-03-15T00:08:06Z
项目社区:https://github.com/imdhemy/jsonable

开源协议:MIT License

下载


Jsonable

Laravel JSON response trait. This trait makes it easy for any controller to return a JSON response with the appropriate HTTP status code.

Installation

Via composer:

  1. composer require imdhemy/jsonable

Usage

All that you need is to use the Jsonable trait inside your controller.

Example:

  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Imdhemy\Jsonable\Jsonable;
  5. class CountryController extends Controller
  6. {
  7. use Jsonable;
  8. public function index()
  9. {
  10. $data = \App\Country::get();
  11. return $this->ok($data, 'countries');
  12. }
  13. }

The previous code will return a JSON response like the following:

  1. {
  2. "countries": [
  3. {
  4. "name": "Egypt",
  5. "capital": "Cairo",
  6. },
  7. ...
  8. ]
  9. }

The parent key is optional, you can ommit it:

  1. $data = \App\Country::get();
  2. return $this->ok($data);

The response will be like the following:

  1. [
  2. {
  3. "name": "Egypt",
  4. "capital": "Cairo",
  5. },
  6. ...
  7. ]

Available methods

Success Methods

Method Status code Description
ok 200 Successful get, patch (return a JSON object)
created 201 Successful post (return a JSON object)
noContent 204 Successful delete

Error Status

Method Status code Description
unauthorized 401 Not authenticated
invalid 403 Authenticated, but no permissions
notFound 404 Not Found
invalid 422 Validation

Extra methods

Method Status code Description
accepted 202 Successful post, delete, path - async
badRequest 400 The request could not be understood by the server due to malformed syntax
paymentRequired 402 Payment required