From 908275ff9f15eaaa41a49f944d02cc147d7bc5a7 Mon Sep 17 00:00:00 2001 From: adrianzofcin Date: Tue, 17 Jan 2023 10:19:44 +0100 Subject: [PATCH] Update ApiResponse.php updated formatting --- src/Helpers/ApiResponse.php | 32 ++++++++++++++++++++++++-------- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/src/Helpers/ApiResponse.php b/src/Helpers/ApiResponse.php index 8b24aee..d76b498 100644 --- a/src/Helpers/ApiResponse.php +++ b/src/Helpers/ApiResponse.php @@ -52,10 +52,10 @@ public static function data(mixed $data): static * @param $resource * @return static */ - public static function collection(mixed $data, $resource = null): static + public static function collection(mixed $pagination, $resource = null): static { - if ($resource) static::$data = ($resource::collection($data))->toResponse(app('request'))->getData(); - else static::$data = $data; + if ($resource) static::$data = (array)($resource::collection($pagination))->toResponse(app('request'))->getData(); + else static::$data = $pagination->toArray(); return new static; } @@ -81,11 +81,27 @@ public static function message(string $message): static */ public static function response(int $statusCode = 200): \Illuminate\Http\JsonResponse { - $response = collect( self::$data); - $response = $response->merge([ - 'code' => self::$code, - 'message' => self::$message ?? __('api.' . self::$code), - ]); + if (gettype(self::$data) === 'array') { + if (key_exists('data', self::$data)) { + $response = collect(self::$data); + $response = $response->merge([ + 'code' => self::$code, + 'message' => self::$message ?? __('api.' . self::$code), + ]); + } else { + $response = [ + 'data' => self::$data, + 'code' => self::$code, + 'message' => self::$message ?? __('api.' . self::$code), + ]; + } + } else { + $response = [ + 'data' => self::$data, + 'code' => self::$code, + 'message' => self::$message ?? __('api.' . self::$code), + ]; + } return response()->json($response)->setStatusCode($statusCode); }