> For the complete documentation index, see [llms.txt](https://core-foundation-doc.rupeshstha.com.np/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://core-foundation-doc.rupeshstha.com.np/http-and-application-layer/responses.md).

# Standardized Responses

Core Foundation enforces a consistent JSON response envelope across the entire application via the `HasApiResponse` trait. This ensures that frontend developers and API consumers always know where to find data, messages, and metadata.

## Success Envelope

All successful responses follow this structure:

```json
{
  "message": "Resource created successfully.",
  "payload": {
    "id": 1,
    "name": "Example"
  }
}
```

If the response is paginated, a `meta` block is added:

```json
{
  "message": "Users fetched.",
  "payload": [...],
  "meta": {
    "pagination": {
      "total": 100,
      "per_page": 15,
      "current_page": 1,
      "last_page": 7,
      "from": 1,
      "to": 15
    }
  }
}
```

## Available Helpers

Use these methods in your controllers:

* `successResponse(string $message, mixed $payload = null)` (200 OK)
* `createdResponse(string $message, mixed $payload = null)` (201 Created)
* `noContentResponse()` (204 No Content)
* `paginatedResponse(string $message, AbstractPaginator $paginator)` (200 OK)

## Error Envelope

Every error response — 4xx and 5xx — always includes the `errors` key. This keeps the shape predictable for all callers regardless of which exception triggered it.

```json
// Validation (422) — errors contains field-level messages
{
  "message": "The given data was invalid.",
  "errors": {
    "email": ["The email field is required."]
  }
}

// Any other error (401, 403, 404, 405, 400, 500) — errors is always present, empty when no field context
{
  "message": "Unauthenticated.",
  "errors": {}
}

// Fatal (500) — exception_id added for log correlation
{
  "message": "An unexpected error occurred. Please contact support with the exception ID.",
  "errors": {},
  "exception_id": "018f2a3b-uuid-here"
}
```

## Payload Resolution

The `payload` parameter in success helpers is automatically resolved:

* **JsonResource**: Calls `resolve()`.
* **Arrayable/Collection**: Calls `toArray()`.
* **Plain Array/Object**: Returned as-is.
