May 27, 2021
0
Level 6
API Resource - with() being omitted from collection
Hello,
I have an API Resource Contact.php which uses the with() method to append extra data to the response:
public function toArray($request)
{
return [
'id' => $this->resource->id,
'firstName' => $this->resource->firstName,
'lastName' => $this->resource->lastName,
'mobile' => $this->resource->mobile
];
}
public function with($request)
{
return [
'status' => 'active'
];
}
when I call the resource class new Contact($contact), the with() data is returned i.e. status:active:
{
"contact": {
"id": "1",
"firstName": "John",
"lastName": "Doe"
},
"status": "active"
}
However, when I turn this into a resource collection new ContactCollection($contacts) or Contact::collection($contacts), the with() data is not returned:
"contacts": [
{
"id": "2",
"firstName": "Jane",
"lastName": "Doe"
},
{
"id": "3",
"firstName": "Jim",
"lastName": "Smith"
}
]
Does anyone know how I can get the with() data returned in a resource collection?
Please or to participate in this conversation.