laravelpivot-tablelaravel-7accessor

Trying to get property 'pivot' of non-object (Laravel 7 - Accessors)


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('App\Product')
        ->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.


Solution

  • Fortunately I found a solution in the end. I changed this piece of code

    foreach ($this->products as $product)
    

    with this one

    foreach ($this->products()->get() as $product) 
    

    and now it works well.