lundi 5 août 2019

How to check if a field exists inside an API resource?

I am trying to find out if a property was selected, if it was selected then merge it within the API resource.

Lets say I have something like this:

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

and both of them will use the same API resource:

return PostResource($postA);
OR
return PostResource($postB);

Then in the API resource, I am trying this to check if a property was selected in the select statement:

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 doesn't work, it always return false. Why? and how can I solve this?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire