Return Only the Data Your Laravel API Needs with whenLoaded()
Imagine your API returns a list of posts.
Your Resource contains:
'author' => new UserResource($this->author),
But your query is:
$posts = Post::latest()->get();
Now the Resource accesses author even though you didn't eager load it.
That's not always what you want.
Use whenLoaded()
Laravel provides:
whenLoaded()
Use it inside your Resource:
'author' => new UserResource(
$this->whenLoaded('author')
),
Now the author is included only when the relationship has already been loaded.
Load It When You Need It
If this API endpoint needs authors:
$posts = Post::with('author')->latest()->get();
return PostResource::collection($posts);
The response includes:
{"id": 1,"title": "Laravel Tips","author": {"id": 5,"name": "Vivek"}
}
Don't Load It?
If you simply do:
$posts = Post::latest()->get();
return PostResource::collection($posts);
the author relationship isn't loaded, so whenLoaded() doesn't force another relationship query just to build the response.
This makes the Resource safer to reuse across different endpoints.
Real Project Example
Suppose you have:
class PostResource extends JsonResource
{
public function toArray($request): array
{
return [
'id' => $this->id,
'title' => $this->title,
'author' => new UserResource(
$this->whenLoaded('author')
),
];
}
}
Now you can use the same Resource for two endpoints.
Simple listing
Post::latest()->paginate(20);
Detailed listing
Post::with('author')->latest()->paginate(20);
The Resource adapts to what the query has loaded.