Jsonable is a package that helps to response or throw exceptions in JSON for Laravel.
Install the latest version using Composer.
1composer require pharaonic/laravel-jsonable
This is how you can create jsonable request.
1php artisan jsonable:request [request-name]
And if you get any errors will be well-formated like this :
1{ 2 "success": false, 3 "code": "MIE-001", 4 "message": null, 5 "errors": [ 6 { 7 "key": "title", 8 "value": "The title field is required." 9 }10 ]11}
This is how you can create jsonable resource.
1php artisan jsonable:resource [resource-name]
And the response will be well-formated like this :
1{ 2 "success": true, 3 "message": "Testing Jsonable Resource", 4 "data": [ 5 { 6 "id": 7, 7 "title": "Pharaonic", 8 "description": "Pharaonic", 9 "keywords": [10 "Pharaonic"11 ],12 "content": "Pharaonic",13 "user_id": 7,14 "created_at": "2022-03-07T07:21:07.000000Z",15 "updated_at": "2022-03-07T07:21:07.000000Z"16 }17 ]18}
You can send jsonable response (success, error and exception) with helper or facade.
1json()->success(array $data, ?string $message = null, ?array $extra = [], int $status = 200, array $headers = []); 2Json::success(...); // Facade3 4json()->errors(array $errors, ?string $code, ?string $message = null, ?array $extra = [], int $status = 400, array $headers = []); 5Json::errors(...); // Facade6 7json()->exception(\Throwable $exception, ?string $code = null, ?string $message = null, ?array $extra = [], int $status = 400, array $headers = []); 8Json::exception(...); // Facade
You can handle the exceptions all over the project just with one step, replace the current ExceptionsHandler with the Jsonable one.
1namespace App\Exceptions; 2 3use Illuminate\Foundation\Exceptions\Handler as ExceptionsHandler; 4use Pharaonic\Laravel\Jsonable\Exceptions\ExceptionHandler; 5use Throwable; 6 7class Handler extends ExceptionsHandler 8class Handler extends ExceptionHandler 9{10 ...11}