Skip to content

Instantly share code, notes, and snippets.

@ahhzaky
Last active July 31, 2024 02:22
Show Gist options
  • Save ahhzaky/b77a31d4c4c505a936b8ed02addb89f7 to your computer and use it in GitHub Desktop.
Save ahhzaky/b77a31d4c4c505a936b8ed02addb89f7 to your computer and use it in GitHub Desktop.
Laravel Response Helpers/ResponseFormatter.php
<?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