Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions src/Illuminate/Http/Resources/Json/JsonResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -158,13 +158,12 @@ public function resolveResourceData(Request $request)
*/
public function toArray(Request $request)
{
if (is_null($this->resource)) {
return [];
}

return is_array($this->resource)
? $this->resource
: $this->resource->toArray();
return match (true) {
is_null($this->resource) => [],
is_array($this->resource) => $this->resource,
$this->resource instanceof Collection => $this->resource->map(fn ($val) => $val instanceof JsonResource ? $val->resolve($request) : $val)->toArray(),
default => $this->resource->toArray($request),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still not positive that this is correct. It's possible that the resource isn't an array, a Collection, or null... in that case, we don't know if there's a toArray() method 🤷

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't it make sense to check $this->resource instanceof Arrayable before calling toArray()?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JsonResource doesn't implement Arrayable anyways. It would have to be a method_exists($this->resource, 'toArray') check. And even then, the toArray() method here differs from Arrayable in its input parameter. 🤷

Also, if it's not an array, null, Arrayable, JsonResource, or Collection, what's the expected behavior? Should it throw an exception? Return an empty array? I have no idea how it's being used by others, so I imagine any choice would cause heartache and strife 😆

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fair enough 👍🏻

};
}

/**
Expand Down
Loading