I have used Laravel 7 for my project. This project has a many-to-many relationship between two tables named "orders" and "products." The following is my code for the "order" model.
public function products()
{
return $this->belongsToMany('AppProduct')
->withPivot('quantity', 'unit_discount', 'unit_price');
}
public function getTotalGrossPriceAttribute()
{
$totalGrossPrice = 0;
foreach ($this->products as $product) {
$totalGrossPrice += ($product->pivot->quantity *
($product->pivot->unit_discount + $product->pivot->unit_price));
}
return $totalGrossPrice;
}
But unfortunately, it brings up this error "Trying to get property ‘pivot’ of non-object"! I would be grateful if to tell me what is exactly wrong with my code.
2
Answers
Fortunately I found a solution in the end. I changed this piece of code
with this one
and now it works well.
You’re trying to access pivot, but it’s not present in the collection. Dump (dd) $this->products, for every collection the pivot is missing. You can’t do like that directly without presence of Order model.
So, instead of $this->products, try calling $order->products.
BTW, you can create another model as Pivot for ProductOrder.