Created
November 11, 2024 05:03
-
-
Save alfaz86/a558845de2d10f307de7ad757f064f69 to your computer and use it in GitHub Desktop.
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 | |
{ | |
/** | |
* Success response | |
* | |
* @param mixed $data | |
* @param string $message | |
* @param int $status | |
* @return JsonResponse | |
*/ | |
protected function successResponse($data, string $message = 'Success', int $status = 200): JsonResponse | |
{ | |
return response()->json([ | |
'status' => 'success', | |
'message' => $message, | |
'data' => $data, | |
], $status); | |
} | |
/** | |
* Error response | |
* | |
* @param string $message | |
* @param int $status | |
* @param mixed|null $errors | |
* @return JsonResponse | |
*/ | |
protected function errorResponse(string $message = 'Error', int $status = 400, $errors = null): JsonResponse | |
{ | |
$response = [ | |
'status' => 'error', | |
'message' => $message, | |
]; | |
if (!is_null($errors)) { | |
$response['errors'] = $errors; | |
} | |
return response()->json($response, $status); | |
} | |
/** | |
* Response for not found resources | |
* | |
* @param string $message | |
* @return JsonResponse | |
*/ | |
protected function notFoundResponse(string $message = 'Resource not found'): JsonResponse | |
{ | |
return $this->errorResponse($message, 404); | |
} | |
/** | |
* Response for unauthorized access | |
* | |
* @param string $message | |
* @return JsonResponse | |
*/ | |
protected function unauthorizedResponse(string $message = 'Unauthorized'): JsonResponse | |
{ | |
return $this->errorResponse($message, 401); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment