PHP code example of kevupton / laravel-json-response
1. Go to this page and download the library: Download kevupton/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/ */
// 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,
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 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);
}
]
];