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

mastermarco's avatar

Add meta data from laravel collection to resource?

I have a laravel collection with resource, to laravel collection I'm adding meta data.

I'm trying to add it like stated in multiple source like laravel docs.

$metaData = ['total' => $elements->count(), 'active_element_id' => $activeElement];
NaviItemResource::collection($elements)->additional([$metaData])

I see $metaData in additional data from collection, but I would need it also in Resource file like stated on image.

Is that possible to add in resource as well?

Example: https://i.stack.imgur.com/rT4eQ.png

0 likes
4 replies
vincent15000's avatar

The meta data you are talking about are additional data for the resource itself and not for the collection. You are adding these meta data to the collection and not to the ressource.

Why do you need these meta data twice in the results ? It will be redundant, won't it ?

mastermarco's avatar

@vincent15000 yeah that's true but can I add data somehow to resource directly? Can I iterate trough collection or what would be the best way to handle it?

1 like
vincent15000's avatar

@mastermarco To add additional data to the resource, you have to do add the $additional property to the resource.

class CategoryResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'recipes_count' => $this->recipes_count,
        ];
    }

    public $additional = [
        'new_data' => 'new_value',
    ];
}

https://laravel.com/api/10.x/Illuminate/Http/Resources/Json/JsonResource.html

What I don't understand is that even the additional data is added to the response :

dd(CategoryResource::collection($categories)); // the additional data is displayed

return CategoryResource::collection($categories); // the additional data isn't displayed

Furthermore I don't know if it's a good idea to add additional data directly by assigning a value to this property.

Please or to participate in this conversation.