2017 © Pedro Peláez
 

extension laravel-json-response

Easy Json responses for laravel

image

kevupton/laravel-json-response

Easy Json responses for laravel

  • Tuesday, May 1, 2018
  • by kevupton
  • Repository
  • 1 Watchers
  • 2 Stars
  • 350 Installations
  • PHP
  • 1 Dependents
  • 0 Suggesters
  • 0 Forks
  • 0 Open issues
  • 11 Versions
  • 17 % Grown

The README.md

Laravel Json Response

An Ethereal Package

Easy way to implement API formatted json responses., (*1)

Format:

{
    "data": {...},
    "errors": [],
    "success": true,
    "status_code": 200,
    "token": null
}

Setup

Install:, (*2)

composer require kevupton/laravel-json-response

Add the service provider to your app config:, (*3)

\Kevupton\LaravelJsonResponse\Providers\LaravelJsonResponseProvider::class,

Add the middleware to your app\Http\Kernel.php, (*4)

Either:, (*5)

// 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, 

Config

Publish the config by using the command:, (*6)

php artisan vendor:publish

Examples

Example returning the data

Usage:, (*7)

Route::get('test', function () {
    return ['hello' => true];
});

Output:, (*8)

{
    "data": {
      "hello": true
    },
    "errors": [],
    "success": true,
    "status_code": 200
}

Example manipulating the JSON directly

You can also set data and tokens directly from this method., (*9)

Usage:, (*10)

Route::get('test', function () {
    json_response()->error('This an example error message')
        ->setStatusCode(\Illuminate\Http\Response::HTTP_BAD_REQUEST);
});

Output:, (*11)

{
    "data": [],
    "errors": [
      "This an example error message"
    ],
    "success": false,
    "status_code": 400
}

Example returning a model

Models are added onto the data using snake_case., (*12)

Usage:, (*13)

Route::get('test', function () {
    return \App\Models\TestModel::find(2);
});

Output:, (*14)

{
    "data": {
        "test_model": {
            "id": 2
        }
    },
    "success": false,
    "status_code": 400
}

Example returning an Arrayable

Arrayable objects have toArray methods, which are merged with the data., (*15)

Usage:, (*16)

Route::get('test', function () {
    return \App\Models\TestModel::paginate();
});

Output:, (*17)

{
    "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
}

Example with validation errors

Usage:, (*18)

Route::get('test', function () {
    throw new \Illuminate\Validation\ValidationException(\Validator::make([], ['test' => 'required']));
});

Output:, (*19)

{
    "data": [],
    "errors": {
        "test": [
            "The test field is required."
        ]
    },
    "success": false,
    "status_code": 422
}

Example Exception

NOTE: APP_DEBUG=true will display a stack trace, (*20)

Usage:, (*21)

Route::get('test', function () {
    throw new Exception('test');
});

Output:, (*22)

{
    "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
}

Exception Handling

Exceptions can be caught by using the config file:, (*23)


<?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); } ] ];

The Versions

01/05 2018

dev-master

9999999-dev

Easy Json responses for laravel

  Sources   Download

MIT

The Requires

  • php >=5.4

 

The Development Requires

by Kevin Upton

laravel json eloquent

01/05 2018

v0.0.10

0.0.10.0

Easy Json responses for laravel

  Sources   Download

MIT

The Requires

  • php >=5.4

 

The Development Requires

by Kevin Upton

laravel json eloquent

16/01 2018

v0.0.9

0.0.9.0

Easy Json responses for laravel

  Sources   Download

MIT

The Requires

  • php >=5.3

 

The Development Requires

by Kevin Upton

laravel json eloquent

14/01 2018

v0.0.8

0.0.8.0

Easy Json responses for laravel

  Sources   Download

MIT

The Requires

  • php >=5.3

 

The Development Requires

by Kevin Upton

laravel json eloquent

14/01 2018

v0.0.7

0.0.7.0

Easy Json responses for laravel

  Sources   Download

MIT

The Requires

  • php >=5.3

 

The Development Requires

by Kevin Upton

laravel json eloquent

30/11 2017

v0.0.6

0.0.6.0

Easy Json responses for laravel

  Sources   Download

MIT

The Requires

  • php >=5.3

 

The Development Requires

by Kevin Upton

laravel json eloquent

30/11 2017

v0.0.5

0.0.5.0

Easy Json responses for laravel

  Sources   Download

MIT

The Requires

  • php >=5.3

 

The Development Requires

by Kevin Upton

laravel json eloquent

29/11 2017

v0.0.4

0.0.4.0

Easy Json responses for laravel

  Sources   Download

MIT

The Requires

  • php >=5.3

 

The Development Requires

by Kevin Upton

laravel json eloquent

28/11 2017

v0.0.3

0.0.3.0

Easy Json responses for laravel

  Sources   Download

MIT

The Requires

  • php >=5.3

 

The Development Requires

by Kevin Upton

laravel json eloquent

28/11 2017

v0.0.2

0.0.2.0

Easy Json responses for laravel

  Sources   Download

MIT

The Requires

  • php >=5.3

 

The Development Requires

by Kevin Upton

laravel json eloquent

28/11 2017

v0.0.1

0.0.1.0

Easy Json responses for laravel

  Sources   Download

MIT

The Requires

  • php >=5.3

 

The Development Requires

by Kevin Upton

laravel json eloquent