Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ranx99's avatar

How to check if field was selected in API resources?

I am trying to find out if a property was selected, if it was selected.. merge it with the resource:

Post::where('id',  $id)->select(['id', 'title',  'subtitle'])->firstOrFail()

Then in the api resouce

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->when(property_exists($this, 'title'), $this->title),
            'subtitle' => $this->when(property_exists($this, 'subtitle'), $this->subtitle)
            // Other fields and relations
        ];
    }
}

But property_exists doesnt work, it always return false.

0 likes
2 replies
rameezisrar's avatar

@ranx99 try this

Post::where('id',  $id)->select('id', 'title',  'subtitle')->firstOrFail();
Ranx99's avatar

@rameezisrar That was not what I was asking for.. I am getting the fields from the database just fine.

I am asking how to check if a field was selected or not inside the API resource..

if it was selected then add it to the resource.. otherwise don't add it.

1 like

Please or to participate in this conversation.