The ApiResponseTrait
in the LaraUtilX
package provides functionality for sending consistent JSON responses for API endpoints.
successResponse(mixed $data = null, int $statusCode = 200): \Illuminate\Http\JsonResponse
: Sends a success response.errorResponse(string $message, int $statusCode): \Illuminate\Http\JsonResponse
: Sends an error response.Send Success Response:
To send a success response, use the successResponse
method:
use omarchouman\LaraUtilX\Traits\ApiResponseTrait;
class MyController extends Controller
{
use ApiResponseTrait;
public function someAction()
{
// Your logic here
$data = [...]; // Data to include in the response
return $this->successResponse($data);
}
}
Send Error Response:
To send an error response, use the errorResponse
method:
use omarchouman\LaraUtilX\Traits\ApiResponseTrait;
class MyController extends Controller
{
use ApiResponseTrait;
public function someAction()
{
// Your logic here
$errorMessage = 'An error occurred'; // Error message
return $this->errorResponse($errorMessage, 422);
}
}
The trait provides consistent JSON responses for API endpoints, enhancing the readability and maintainability of API code.
data
key containing the provided data and a success
key set to true.error
key containing the provided error message and a success
key set to false.You can publish this trait through the below command
php artisan vendor:publish --tag=lara-util-x-api-response-trait
This trait simplifies the process of sending API responses, ensuring a consistent format across different endpoints.