Interview frequency: …
Short answer
They act as a Transformation Layer separating database table structure from the API response, preventing sensitive fields from leaking and standardizing data formatting.
Explanation
Returning $user directly as JSON couples the API to the database table structure; changing a column name could break mobile apps and external clients, and sensitive columns might leak. JsonResource classes let you select and rename fields, conditionally include relationships with whenLoaded(), and format dates consistently.
Code example
class UserResource extends JsonResource {
public function toArray(Request $request): array {
return [
'id' => $this->id,
'fullName' => $this->name,
'posts' => PostResource::collection($this->whenLoaded('posts')),
];
}
}Common mistakes
- Loading relationships directly inside a Resource, recreating the N+1 problem instead of using $this->whenLoaded().