forge/app/Traits/ApiResponses.php

40 lines
908 B
PHP
Raw Normal View History

<?php
namespace App\Traits;
use Illuminate\Http\JsonResponse;
trait ApiResponses
{
2024-09-11 23:08:58 -04:00
/**
* Return a success JSON response.
*/
protected function success(string $message, ?array $data = []): JsonResponse
{
return $this->baseResponse(message: $message, data: $data, code: 200);
}
2024-09-11 23:08:58 -04:00
/**
* The base response.
*/
private function baseResponse(?string $message = '', ?array $data = [], ?int $code = 200): JsonResponse
{
$response = [];
$response['message'] = $message;
if ($data) {
$response['data'] = $data;
}
$response['status'] = $code;
return response()->json($response, $code);
}
2024-09-11 23:08:58 -04:00
/**
* Return an error JSON response.
*/
protected function error(string $message, int $code): JsonResponse
{
return $this->baseResponse(message: $message, code: $code);
}
}