skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.


  2. 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.

    <?php
    namespace AppModels;
    use IlluminateDatabaseEloquentRelationsPivot;
    
    class ProductOrder extends Pivot
    {
        //
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search