Level 3
Can't you just turn this:
return new TopicCollection(Topic::all());
to this:
return TopicResource::collection(Topic::all());
1 like
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi, previous PHP 8 I used my API Resources like that:
class TopicResource extends JsonResource
{
* TopicResource constructor.
/**
* Transform the resource into an array.
*
* @param Request $request
* @return array
*/
public function toArray($request)
{
/** @var Topic $this */
return [
'id' => $this->id,
'title' => $this->title,
'active' => $this->active,
'country_id' => $this->country->id ?? null,
'order_id' => $this->order_id,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at
];
}
}
and on my collection I used transform to return it
/**
* Transform the resource collection into an array.
*
* @param Request $request
* @return array
*/
public function toArray($request)
{
return [
'data' => $this->collection->transform(function (Topic $topic) {
return new TopicResource($topic);
}),
];
}
The call is simple
return new TopicCollection(Topic::all());
But with PHP 8 I got an exception
"message": "App\Http\Resources\TopicCollection::App\Http\Resources\{closure}(): Argument #1 ($topicResource) must be of type App\Models\Topic, App\Http\Resources\TopicResource given",
So I changed my TopicCollection to
'data' => $this->collection->transform(function (TopicResource $topicResource) {
return new TopicResource($topicResource->resource, $this->withTakes);
}),
and this works. Can anybody explain me this behavior?
Please or to participate in this conversation.