Enhanced API Response Trait

The ApiResponseTrait in the LaraUtilX package provides a robust and standardized way to send JSON responses for API endpoints, including support for meta information, debug data, exception handling, and pagination.

Methods

  1. successResponse(mixed $data = null, string $message = 'Request successful.', int $statusCode = 200, array $meta = []): \Illuminate\Http\JsonResponse
    • Sends a standardized success response with optional data, message, status code, and meta information.
  2. errorResponse(string $message = 'Something went wrong.', int $statusCode = 500, array $errors = [], mixed $debug = null): \Illuminate\Http\JsonResponse
    • Sends a standardized error response with optional error details and debug data (debug data is only included if app.debug is true).
  3. exceptionResponse(\Throwable $e, int $statusCode = 500): \Illuminate\Http\JsonResponse
    • Handles exception responses, logs the error, and returns a detailed debug payload if in debug mode.
  4. paginatedResponse($paginator, string $message = 'Data fetched successfully.'): \Illuminate\Http\JsonResponse
    • Sends a paginated response with meta information about pagination.

Usage

1. Send Success Response

use LaraUtilX\Traits\ApiResponseTrait;

class MyController extends Controller
{
    use ApiResponseTrait;

    public function someAction()
    {
        $data = [...]; // Your data
        $meta = ['custom' => 'value'];
        return $this->successResponse($data, 'Fetched successfully.', 200, $meta);
    }
}

2. Send Error Response (with optional debug info)

use LaraUtilX\Traits\ApiResponseTrait;

class MyController extends Controller
{
    use ApiResponseTrait;

    public function someAction()
    {
        $errors = ['field' => 'Invalid value'];
        $debug = ['trace' => '...'];
        return $this->errorResponse('Validation failed.', 422, $errors, $debug);
    }
}

3. Exception Handling

use LaraUtilX\Traits\ApiResponseTrait;

class MyController extends Controller
{
    use ApiResponseTrait;

    public function someAction()
    {
        try {
            // ...
        } catch (\Throwable $e) {
            return $this->exceptionResponse($e);
        }
    }
}

4. Paginated Response

use LaraUtilX\Traits\ApiResponseTrait;
use Illuminate\Pagination\LengthAwarePaginator;

class MyController extends Controller
{
    use ApiResponseTrait;

    public function list()
    {
        $paginator = User::paginate(10);
        return $this->paginatedResponse($paginator);
    }
}

Result

Success Response:

{
  "success": true,
  "message": "Request successful.",
  "data": { /* your data */ },
  "meta": { /* optional meta */ }
}

Error Response:

{
  "success": false,
  "message": "Something went wrong.",
  "errors": [ /* error details */ ],
  "debug": { /* debug info, only in debug mode */ }
}

Exception Response:

{
  "success": false,
  "message": "Internal server error.",
  "errors": [],
  "debug": {
    "exception": "ExceptionClassName",
    "message": "Exception message.",
    "trace": [ /* stack trace */ ]
  }
}

Paginated Response:

{
  "success": true,
  "message": "Data fetched successfully.",
  "data": [ /* items */ ],
  "meta": {
    "pagination": {
      "total": 100,
      "count": 10,
      "per_page": 10,
      "current_page": 1,
      "total_pages": 10
    }
  }
}

Publish

You can publish this trait through the below command:

php artisan vendor:publish --tag=lara-util-x-api-response-trait



This enhanced trait simplifies the process of sending API responses, ensuring a consistent, extensible, and debuggable format across your Laravel endpoints.