PHP code example of faridibin / laravel-json-response

1. Go to this page and download the library: Download faridibin/laravel-json-response library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

faridibin / laravel-json-response example snippets


\Faridibin\LaravelJsonResponse\Providers\LaravelJsonResponseProvider::class,

// Formats all responses in json. Catches errors listed in config and JsonResponseErrorExceptions
Faridibin\LaravelJsonResponse\Middleware\OutputJsonResponse, 

// Extends the OutputJsonResponse to catch all errors, to keep the JSON output
Faridibin\LaravelJsonResponse\Middleware\CatchAllExceptions, 

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

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

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

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

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

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



use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Response;
use Illuminate\Validation\ValidationException;
use Faridibin\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);
        }
    ]
];
bash
php artisan vendor:publish
json
{
    "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
}