'Laravel resource collection, return data from resource to collection
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?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
