API Response Trait

The ApiResponseTrait in the LaraUtilX package provides functionality for sending consistent JSON responses for API endpoints.

Methods

  1. successResponse(mixed $data = null, int $statusCode = 200): \Illuminate\Http\JsonResponse: Sends a success response.
  2. errorResponse(string $message, int $statusCode): \Illuminate\Http\JsonResponse: Sends an error response.

Usage

  1. 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);
       }
    }
  2. 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);
       }
    }

Result

The trait provides consistent JSON responses for API endpoints, enhancing the readability and maintainability of API code.

  • Success Result: The successResponse method returns a JSON response with a data key containing the provided data and a success key set to true.
  • Error Result: The errorResponse method returns a JSON response with an error key containing the provided error message and a success key set to false.

Publish

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.