Isn't that what you are doing in that example, using when()?
https://laravel.com/docs/8.x/eloquent-resources#conditional-attributes
You have access to the request
'start_date' => $this->when($request->input('show_start'), $this->start_date),
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
In my API resource, along with other fields, I return a user resource like this:
....
'user' => new UserResource($this->whenLoaded('user')),
'start_date' => $this->when($this->start_date, $this->start_date),
'end_date' => $this->when($this->end_date, $this->end_date),
....
But sometimes I do not want to include all the user's data. if it were a collection I could do:
'media' => MediaResource::collection($this->whenLoaded('media'))->except('some_field')
How can I exclude certain fields conditionally on a API resource?
@panthro Ok this then
'user' => new UserResource($this->whenLoaded('user', function() {
$user = $this->resource->user;
$fake = new User;
$fake->username = $user->username;
return $fake;
}),
Please or to participate in this conversation.