Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

matz's avatar
Level 14

Laravel 8 PHP 8 and API Eloquent Resources

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?

0 likes
2 replies
andyabihaidar's avatar

Can't you just turn this:

return new TopicCollection(Topic::all());

to this:

return TopicResource::collection(Topic::all());
1 like
matz's avatar
Level 14

Thanks! My code was simplified, I pass conditions to the Resource. Is it still possible that way?

And I'm still confused why it worked with PHP 7.4 :-)

Please or to participate in this conversation.