Supposed i have an accessor
to my Product
model
class Product extends Model
{
public function getIncomeAttribute() {
$sub_total = $this->price * $this->quantity;
$discount = round((10 / 100) * $sub_total, 2);
return round(($sub_total - $discount), 2);
}
public function orders(){
return $this->belongsToMany(Order::class)->withPivot('quantity')->withTimestamps();
}
}
My product model has a many to many relationship with order, this is my order model
class Order extends Model
{
public function products(){
return $this->belongsToMany(Product::class)->withPivot('quantity')->withTimestamps();
}
}
from my order how can i access the accessor in my product model? i tried this $this->products->quantity
, but the error is Property [income] does not exist on this collection instance
this is my OrderResource
that extends JsonResource
where i tried to used the $this->products->income
public function toArray($request){
$sub_total= 0;
foreach($this->products as $product){
$sub_total += ($product->pivot->quantity * $product->price);
}
$discount = round((10 / 100) * $sub_total, 2);
$total = round(($sub_total - $discount), 2);
$sub_total = round($sub_total,2);
return [
'id' => $this->id,
'address' => $this->address,
'sub_total' => $sub_total,
'discount' => $discount,
'total_price' => $this->products->quantity,
'created_at' => Carbon::parse($this->created_at)->format('F d, Y h:i:s A'),
'customer' => $this->user,
'items' => ProductsResource::collection($this->products)
];
}
Create
subTotal
accessor in Order ModelOrder Model
Now use it in
OrderResource
public function toArray($request){
}
Note: When you fetch
Order
then eager loadProduct