Skip to content

Instantly share code, notes, and snippets.

@axeladriant
Created September 15, 2016 18:30
Show Gist options
  • Select an option

  • Save axeladriant/af5fa55978825f3725df1304e867745a to your computer and use it in GitHub Desktop.

Select an option

Save axeladriant/af5fa55978825f3725df1304e867745a to your computer and use it in GitHub Desktop.
LARAVEL: Nicer responses with Response Macros
<?php
/** USAGE:
* return response()->success($data);
* return response()->notFound();
* return response()->created($createdResource);
* return response()->error($errorMessage, $errorCode);
*/
use Symfony\Component\HttpFoundation\Response as ResponseCode;
use Response;
// Success
Response::macro('success', function ($data) {
// Handles boolean success responses.
// WARNING: This might be an unexpected problem or
// a wrongly asigned response.
$booleanData = is_bool($data);
if ($booleanData) {
return Response::json(null, ResponseCode::HTTP_NO_CONTENT);
}
// Regular success response
return Response::json($data, ResponseCode::HTTP_OK);
});
// Created
Response::macro('created', function ($data) {
return Response::json($data, ResponseCode::HTTP_CREATED);
});
// Deleted and OK
$handleDeleteAndOkResponses = function () {
return Response::json(null, ResponseCode::HTTP_NO_CONTENT);
};
Response::macro('deleted', $handleDeleteAndOkResponses);
Response::macro('ok', $handleDeleteAndOkResponses);
// Error
Response::macro('error', function ($message, $statusCode = ResponseCode::HTTP_INTERNAL_SERVER_ERROR) {
return Response::json(
['error' => $message],
$statusCode
);
});
// Error: Not found
Response::macro('notFound', function ($message = 'not_found') {
return Response::json(
['error' => $message],
ResponseCode::HTTP_NOT_FOUND
);
});
@michini

michini commented Sep 17, 2016

Copy link
Copy Markdown

ola amigo soy nuevo en esto una consulta, donde puedo guardar este archivo para poder darle uso

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment