Last active
July 31, 2024 02:22
-
-
Save ahhzaky/b77a31d4c4c505a936b8ed02addb89f7 to your computer and use it in GitHub Desktop.
Laravel Response Helpers/ResponseFormatter.php
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\Helpers; | |
/** | |
* Format response. | |
*/ | |
class ResponseFormatter | |
{ | |
/** | |
* API Response | |
* | |
* @var array | |
*/ | |
protected static $response = [ | |
'meta' => [ | |
'code' => 200, | |
'status' => 'success', | |
'message' => null, | |
], | |
'data' => null, | |
]; | |
/** | |
* Give success response. | |
*/ | |
public static function success($data = null, $message = null) | |
{ | |
self::$response['meta']['message'] = $message; | |
self::$response['data'] = $data; | |
return response()->json(self::$response, self::$response['meta']['code']); | |
} | |
/** | |
* Give error response. | |
*/ | |
public static function error($data = null, $message = null, $code = 400) | |
{ | |
self::$response['meta']['status'] = 'error'; | |
self::$response['meta']['code'] = $code; | |
self::$response['meta']['message'] = $message; | |
self::$response['data'] = $data; | |
return response()->json(self::$response, self::$response['meta']['code']); | |
} | |
} | |
<?php | |
namespace App\Helpers; | |
/** | |
* Format response. | |
*/ | |
class ResponseFormatter | |
{ | |
/** | |
* API Response | |
* | |
* @var array | |
*/ | |
protected static $response = [ | |
'meta' => [ | |
'code' => 200, | |
'status' => 'success', | |
'message' => null, | |
], | |
'data' => null, | |
]; | |
/** | |
* Give success response. | |
*/ | |
public static function success($data = null, $message = null) | |
{ | |
self::$response['meta']['message'] = $message; | |
self::$response['data'] = $data; | |
return response()->json(self::$response, self::$response['meta']['code']); | |
} | |
/** | |
* Give error response. | |
*/ | |
public static function error($data = null, $message = null, $code = 400) | |
{ | |
self::$response['meta']['status'] = 'error'; | |
self::$response['meta']['code'] = $code; | |
self::$response['meta']['message'] = $message; | |
self::$response['data'] = $data; | |
return response()->json(self::$response, self::$response['meta']['code']); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment