To return an empty array as {} you can cast it
'foo' => (object) [],
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I'm developing an API and need to be able to output empty arrays and objects in the returned JSON. However, I'm running into a problem where empty objects/dicts are returned as empty arrays.
Example Request Body:
{
"attributes": {
"empty_array": [],
"empty_object": {}
}
}
Actual Response:
{
"attributes": {
"empty_array": [],
"empty_object": []
}
}
Expected Response:
{
"attributes": {
"empty_array": [],
"empty_object": {}
}
}
In the model, I am casting the attribute to an ArrayObject:
protected $casts = [
'attributes' => AsArrayObject::class
];
And then in the controller, the model is handed off to an API resource:
public function store(StoreCustomerRequest $request)
{
return new CustomerResource(Customer::create($request->validated()));
}
The API resource:
public function toArray($request)
{
return [
'attributes' => $this->attributes
];
}
I'm not sure what I'm missing or doing wrong to be able to have all instances of arrays and objects/dicts (no matter the nesting level) represented in the returned JSON.
Please or to participate in this conversation.