I have 2 variables that I want to send to resource and show them via API like below:
return new RoomDetailResource($data_array, $sum);
and the resource I have written is like below:
class RoomDetailResource extends JsonResource
{
/**
* @var
*/
public $sum;
/**
* Create a new resource instance.
*
* @param mixed $resource
* @return void
*/
public function __construct($resource, $sum)
{
// Ensure you call the parent constructor
parent::__construct($resource);
$this->resource = $resource;
$this->sum = $sum;
}
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'sum' => $this->sum
];
}
}
now what I get is the error:
"message": "Trying to get property 'id' of non-object", "status_code": 500,
but if I want to show sum
it shows without any problem now here is how I want my API response to look like:
{
id: 1,
sum: 200
},
{
id: 2,
sum: 200
}
Note that sum
is the same for all and I just want to repeat it in objects or show them at the end of the API response as a property.
thanks