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

vielhuber's avatar

Why does Resource Collection not use the columns specified in the underlying Resource?

Hello!

Consider this code:

class ExampleResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'foo' => 'bar'
        ];
    }
}

class ExampleCollection extends ResourceCollection
{
    public function toArray($request)
    {
        return [
            'data' => $this->collection
        ];
    }
}

When calling

return new ExampleCollection(Example::all());

All columns (including created_at and updated_at) are included, NOT only those specified in the ExampleResource.

Why is this?

The only way of getting this to work is to use this:

class ExampleCollection extends ResourceCollection
{
    public function toArray($request)
    {
        return [
            'data' => ExampleResource::collection($this->collection)
        ];
    }
}

Is this correct?!

0 likes
2 replies
burlresearch's avatar

Ya what you've got seems pretty much correct. I find this a little awkward too - I kinda thought the Resource and Collection would somehow be tied a little more closely when I first wrestled with this concept.

Seems that Taylor wanted to leave them pretty decoupled based on his comments in the docs, which I understand - to have the Collection be a little more customizable.

But - as you're suggesting, I think - it would be pretty natural to have the collection just be an augmented representation of the Resource. You've picked up on the ExampleResource::collection which is kind of a halfway ground to doing that extension, but it's not really clear.

Maybe this would a candidate for improvement in future Laravel version? Interesting ...

Have you looked at Fractal, as a potential alternative:

https://fractal.thephpleague.com/

When I was considering working with Resources last, I think I used Fractal instead. It's maybe a little cleaner in some ways.

vielhuber's avatar

Hello! Thanks for your concise and extensive answer, very helpful.

Please or to participate in this conversation.