Last active
July 2, 2022 07:07
-
-
Save fajarwz/6e4fb6633006f4d56307a0a29c5fdac8 to your computer and use it in GitHub Desktop.
API Response for PHP / Laravel with meta properties
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// app/helpers.php in Laravel | |
// add this file to "files" in composer.json | |
// "autoload": { | |
// "psr-4": { | |
// ... | |
// }, | |
// "files": [ | |
// "app/helpers.php" | |
// ] | |
// }, | |
// use it | |
// return successResponse([ | |
// 'user' => $user, | |
// ]); | |
function apiResponse($data = null, $message = null, $code = 404, $status = 'error') { | |
return [ | |
'meta' => [ | |
'code' => $code, | |
'status' => $status, | |
'message' => $message, | |
], | |
'data' => $data, | |
]; | |
} | |
function successResponse($data = null, $message = null) | |
{ | |
return response()->json( | |
apiResponse($data, $message, 200, 'success'), 200 | |
); | |
} | |
function errorResponse($data = null, $message = null, $code = 400) | |
{ | |
return response()->json( | |
apiResponse($data, $message, $code), $code | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment