all api response codes laravel code example
Example 1: laravel api response trait
trait RespondsWithHttpStatus
{
protected function success($message, $data = [], $status = 200)
{
return response([
'success' => true,
'data' => $data,
'message' => $message,
], $status);
}
protected function failure($message, $status = 422)
{
return response([
'success' => false,
'message' => $message,
], $status);
}
}
Example 2: encode in laravel api
protected function jsonResponse($data, $code = 200)
{
return response()->json($data, $code,
['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE);
}
$this->jsonResponse($data);