Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GimmeMylanta's avatar

API response macro

Hey Guys,

I'm giving the Laravel Macroable thingo a shot for the first time to create my API responses instead of putting them in something like the BaseController.

I was wondering if you could have a look at the code below and tell me if there is anything I can improve on in regards to keeping the response as close to 'standards' as possible.

Any changes, improvements or advice would be greatly appreciated.

public function boot()
{
    Response::macro('success', function ($message, $data, $status = 200) {
        return Response::json([
            'success' => true,
            'message' => $message,
            'data' => $data
        ], $status);
    });

    Response::macro('error', function ($message, $errorMessages = [], $status = 400) {

        $response = [
            'success' => false,
            'message' => $message,
        ];

        if (!empty($errorMessages)) {
            $response['data'] = $errorMessages;
        }

        return Response::json($response, $status);
    });
}
0 likes
1 reply
bugsysha's avatar

For me those kind of helpers greatly vary from project to project so I started to avoid them. Also being as much explicit as possible helps readability in long term. I think that only time I ever return a response is for redirects so for me there is not much use from this. Especially for JSON responses which are handled perfectly if you use something like Eloquent resources https://laravel.com/docs/master/eloquent-resources

Please or to participate in this conversation.