Supposed I have an API response of a Product
{
data: [
{
id: 3,
name: "Test Product",
price: "158.21",
quantity: 4,
income: 569.56
},
{
id: 4,
name: "Test Product",
price: "58.21",
quantity: 3,
income: 157.17
},
]
}
is there a way where i can add a total of all the income of a product just like this?
{
data: [
{
id: 3,
name: "Test Product",
price: "158.21",
quantity: 4,
income: 569.56
},
{
id: 4,
name: "Test Product",
price: "58.21",
quantity: 3,
income: 157.17
},
],
total: 726.73
}
this is my class OrderProductResource
that extends JsonResource
public function toArray($request)
{
$quantity = 0;
$overAllTotal = 0;
foreach($this->orders as $order){
$quantity += $order->pivot->quantity;
}
$sub_total = round($this->price * $quantity,2);
$discount = round((10 / 100) * $sub_total, 2);
$totalIncome = round(($sub_total - $discount), 2);
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
'quantity' => $quantity,
'income' => $totalIncome,
];
}
i tried to use the with
method in laravel but the API response is still the same.
this is my controller
public function index(){
$errorFound = false;
$error = ['error' => 'No Results Found'];
$products = Product::with('orders');
if (request()->has('q')) {
$keyword = '%'.request()->get('q').'%';
$builder = $products->where('name', 'like', $keyword);
$builder->count() ? $products = $builder : $errorFound = true;
}
return $errorFound === false ? OrderProductResourceCollection::collection($products->latest()->paginate()) : $error;
}