PHPackages                             kevupton/laravel-json-response - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. kevupton/laravel-json-response

ActiveExtension[Database &amp; ORM](/categories/database)

kevupton/laravel-json-response
==============================

Easy Json responses for laravel

v0.0.11(7y ago)161.5k3[1 issues](https://github.com/kevupton/laravel-json-response/issues)MITPHPPHP &gt;=5.4

Since Nov 28Pushed 7y ago2 watchersCompare

[ Source](https://github.com/kevupton/laravel-json-response)[ Packagist](https://packagist.org/packages/kevupton/laravel-json-response)[ RSS](/packages/kevupton-laravel-json-response/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (12)Used By (0)

Laravel Json Response
=====================

[](#laravel-json-response)

An [Ethereal](https://github.com/kevupton/ethereal/wiki) Package
----------------------------------------------------------------

[](#an-ethereal-package)

Easy way to implement API formatted json responses.

#### Format:

[](#format)

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

Setup
-----

[](#setup)

Install:

```
composer require kevupton/laravel-json-response
```

Add the service provider to your app config:

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

Add the middleware to your `app\Http\Kernel.php`

Either:

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

[](#config)

Publish the config by using the command:

```
php artisan vendor:publish
```

Examples
--------

[](#examples)

#### Example returning the data

[](#example-returning-the-data)

Usage:

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

Output:

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

---

#### Example manipulating the JSON directly

[](#example-manipulating-the-json-directly)

You can also set data and tokens directly from this method.

Usage:

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

Output:

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

---

#### Example returning a model

[](#example-returning-a-model)

Models are added onto the data using snake\_case.

Usage:

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

Output:

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

---

#### Example returning an Arrayable

[](#example-returning-an-arrayable)

Arrayable objects have toArray methods, which are merged with the data.

Usage:

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

Output:

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

[](#example-with-validation-errors)

Usage:

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

Output:

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

---

#### Example Exception

[](#example-exception)

*NOTE: `APP_DEBUG=true` will display a stack trace*

Usage:

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

Output:

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

[](#exception-handling)

Exceptions can be caught by using the config file:

```
