Created
March 25, 2024 20:41
-
-
Save jovialcore/a0f24caf4afe7222c4c798c00e822f14 to your computer and use it in GitHub Desktop.
A reusable trait I use for returning api response.
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 | |
namespace App\Traits; | |
use Illuminate\Http\JsonResponse; | |
trait ApiResponse | |
{ | |
protected function success(array|object $data = [], string $message = '', int $code = 200): JsonResponse | |
{ | |
return $this->res('success', message: $message, data: $data, code: $code); | |
} | |
protected function error(array|object $data = [], string $message = '', int $code = 400): JsonResponse | |
{ | |
return $this->res('Invalid request', $message, $data, $code); | |
} | |
protected function notFound(array|object $data = [], string $message = '', int $code = 404): JsonResponse | |
{ | |
return $this->res('not_found', $message, $data, $code); | |
} | |
protected function serverError(array|object $data = [], string $message = '', int $code = 500): JsonResponse | |
{ | |
return $this->res('server_error', $message, $data, $code); | |
} | |
protected function notPermitted(array|object $data = [], string $message = '', int $code = 405): JsonResponse | |
{ | |
return $this->res('not_permitted', $message, $data, $code); | |
} | |
protected function res(string $type, string $message, array|object $data, int $code): JsonResponse | |
{ | |
return response()->json( | |
[ | |
'response' => ($type == 'success') ? true : false, | |
'type' => $type, | |
'message' => $message, | |
'status' => $code, | |
'data' => $data, | |
] | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment