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
Jan 9, 2020
1
Level 5
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);
});
}
Please or to participate in this conversation.