this is a fork from https://github.com/appstract/laravel-response-macros, I change the output format to replicate the fractal standard, plus a message property:
{
"success": true,
"status": 200,
"message": "congratulations!",
"data": {
// Some response object
},
"error": null
}
{
"success": false,
"status": 500,
"message": "Bad request!",
"data": null,
"error": {
// Some response object
}
}
This package is a collection of custom response macros that you can re-use in a variety of your routes and controllers.
Since this is a fork from the original laravel-response-macros package, the best way to install it is using the VCS repositories feature. Add the following lines to your composer.json file:
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/jecovier/laravel-response-macros"
}
],
"require": {
"jecovier/laravel-response-macros": "^1.0.8"
}
}
and run:
composer install
return response()->message('hello world!', 200);
Result
{
"message": "hello world!"
}
With the Http Status Code: 200
return response()->error('Something went wrong', $statuscode = 400, $errorObject = null);
Result
{
"success": false,
"status": 400,
"message": "Something went wrong",
"data": null,
"error": {
// Some error object or null
}
}
With the Http Status Code: 400
return response()->success('congratulations!', ['some' => 'data'], $statuscode = 200);
Result
{
"success": true,
"status": 200,
"message": "congratulations!",
"data": {
"some": "data"
},
"error": null
}
With the Http Status Code: 200
If you want to format all Api request Exceptions automatically, open your handler file (app/Exceptions/Handler) and set the $formatApiResponse protected variable to true:
class Handler extends ExceptionHandler
{
protected $formatApiResponse = true;
.
.
.
}
Now, if the request expects a Json and there is an Exception, the response would be converted automatically to an error response object.
$ composer test
Contributions are welcome, thanks to y'all :)
Appstract is a small team from The Netherlands. We create (open source) tools for webdevelopment and write about related subjects on Medium. You can follow us on Twitter, buy us a beer or support us on Patreon.
The MIT License (MIT). Please see License File for more information.