Skip to content

jecovier/laravel-response-macros

 
 

Repository files navigation

FORK

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 response

{
    "success": true,
    "status": 200,
    "message": "congratulations!",
    "data": {
        // Some response object
    },
    "error": null
}

Error response

{
    "success": false,
    "status": 500,
    "message": "Bad request!",
    "data": null,
    "error": {
        // Some response object
    }
}

Laravel Response Macros

Latest Version on Packagist Total Downloads Software License Build Status

This package is a collection of custom response macros that you can re-use in a variety of your routes and controllers.

Installation

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

Usage

Message

return response()->message('hello world!', 200);

Result

{
    "message": "hello world!"
}

With the Http Status Code: 200

Error

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

Success

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

Auto Format all exceptions

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.

Testing

$ composer test

Contributing

Contributions are welcome, thanks to y'all :)

About Appstract

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.

License

The MIT License (MIT). Please see License File for more information.