Created
January 6, 2021 16:24
-
-
Save ahmedsayedabdelsalam/2016e2f57990258430c15a7359fc7895 to your computer and use it in GitHub Desktop.
api responder
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\Http\Traits; | |
use Illuminate\Http\JsonResponse; | |
use Illuminate\Http\Resources\Json\JsonResource; | |
trait ApiResponder | |
{ | |
/** | |
* @param $data | |
* @param null $message | |
* @param int $code | |
* @return JsonResponse | |
*/ | |
protected function successResponse($data, $message = null, $code = 200): JsonResponse | |
{ | |
if ($data instanceof JsonResource) { | |
return $data->additional([ | |
'status'=> 'success', | |
'message' => $message, | |
]) | |
->response() | |
->setStatusCode($code); | |
} | |
return response()->json([ | |
'status'=> 'success', | |
'message' => $message, | |
'data' => $data, | |
], $code); | |
} | |
/** | |
* @param null $message | |
* @param $code | |
* @return JsonResponse | |
*/ | |
protected function errorResponse($message, $code): JsonResponse | |
{ | |
return response()->json([ | |
'status'=>'error', | |
'message' => $message, | |
'data' => null, | |
], $code); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment