Search code examples
phplaravelcartlaravel-8

Laravel 8: Trying to get property 'price' of non-object


I'm trying to make an online store with Laravel 8 and for my cart.blade.php I coded this:

<div class="text-right mt-4">
    <label class="text-muted font-weight-normal m-0">Final Price</label>

    @php
        $totalPrice = Cart::all()->sum(function($cart) {
        return $cart['product']->price * $cart['quantity'];
        });
    @endphp
    <div class="text-large"><strong>{{ $totalPrice }} is price</strong></div>
</div>

And method all() goes like this:

public function all()
    {
        $cart = $this->cart;
        $cart = $cart->map(function($item) {
            return $this->withRelationshipIfExist($item);
        });

        return $cart;
    }

So how to fix this issue? I would really appreciate any idea or suggestion from you guys...

Thanks in advance.


Solution

  • The error is telling you that $cart is not an object. This happens when it is not being set correctly.

    If your all() function is in your Cart model, then you actually don't want $this->cart. You would simply want $cart = $this.