Laravel resource collection, return data from resource to collection

Viewed 553

I'm using Laravel v6 and writing Resource and resource collection. I would like to use some data from the resource inside the resource collection. For example, I have the following UserResource and UserCollection:

class UserResource extends JsonResource
{
    public $data = 0;
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $this->data + = 5; 
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
    public function getAdditionalData(){
            return $this->data;
    }
}

class UserCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'data' => $this->collection,
            'additional-data' => [
                (new UserResource(null))->getAdditionalData(),
            ],
        ];
    }
}

I want to return some data calculated in the resource and use it in the resource collection. The value that i'm receiving is 0 while I'm expecting 5. How can I return this data from the resource into the collection?

1 Answers

You have not called the resource's toArray() function, so your data is not being incremented. Try calling the function first, for example:

$userResource = new UserResource(null);
$userResource->toArray(); // Returns an array. Your data is incremented here
$additionalData = $userResource->getAdditionalData(); // what you actually want

It would help if you provided a bigger picture of what you are trying to do.

Related