Laravel API resources for JSON transformation

6560
0

API resources transform Eloquent models into JSON responses with full control over structure and data exposure. I create resource classes that extend JsonResource and define a toArray() method returning the desired JSON structure. Resources hide sensitive attributes, format dates, include computed properties, and conditionally include relationships. The whenLoaded() method includes relationships only if they're eager loaded, preventing N+1 queries. Resource collections handle arrays of models, while preserveQuery() maintains pagination links. Anonymous resources work for one-off transformations without creating dedicated classes. The with() method adds meta information to all responses. This layer provides consistent API responses and decouples database structure from API contracts.