Created
February 20, 2024 08:00
-
-
Save tsukifell/88ecd5f84751105a40cc20abf89ec26c to your computer and use it in GitHub Desktop.
ResponseHelper for returning a JSON Response in PHP Laravel
This file contains hidden or 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\Helper; | |
use Exception; | |
use Illuminate\Database\Eloquent\ModelNotFoundException; | |
use Illuminate\Http\JsonResponse; | |
use Symfony\Component\HttpFoundation\Response as ResponseAlias; | |
class ResponseHelper | |
{ | |
public static function genericResponse($success, $message, $statusCode): JsonResponse | |
{ | |
return response()->json([ | |
'success' => $success, | |
'message' => $message | |
], $statusCode); | |
} | |
public static function genericDataResponse($success, $message, $data, $statusCode): JsonResponse | |
{ | |
return response()->json([ | |
'success' => $success, | |
'message' => $message, | |
'data' => $data | |
], $statusCode); | |
} | |
public static function genericException(Exception $e): JsonResponse | |
{ | |
return self::genericResponse(false, $e->getMessage(), ResponseAlias::HTTP_INTERNAL_SERVER_ERROR); | |
} | |
public static function genericSuccessResponse($message, $data): JsonResponse | |
{ | |
return self::genericDataResponse(true, $message, $data, ResponseAlias::HTTP_OK); | |
} | |
public static function genericDataIsEmpty(): JsonResponse | |
{ | |
return self::genericResponse(true, 'No Content Provided', ResponseAlias::HTTP_NO_CONTENT); | |
} | |
public static function genericDataNotFound(ModelNotFoundException $e): JsonResponse | |
{ | |
return self::genericResponse(false, 'Data not found ' . $e->getMessage(), ResponseAlias::HTTP_NOT_FOUND); | |
} | |
public static function genericDataUpdated($type): JsonResponse | |
{ | |
return self::genericResponse(true, $type . ' updated successfully', ResponseAlias::HTTP_OK); | |
} | |
public static function genericDataDeleted($type): JsonResponse | |
{ | |
return self::genericResponse(true, $type . ' deleted successfully!', ResponseAlias::HTTP_OK); | |
} | |
public static function genericDataCreated($type): JsonResponse | |
{ | |
return self::genericResponse(true, $type . ' created successfully!', ResponseAlias::HTTP_CREATED); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment