Laravel Eloquent sum relation's column through other relation
<p>Let's say I have these modules:</p>

<ul>
<li>Coupon</li>
<li>Order (.., coupon_id)</li>
<li>Item (..., order_id, price)</li>
</ul>

<p>And there are those relations:</p>

<ul>
<li><code>Coupon</code> <strong>Has Many</strong> <code>Order</code>.</li>
<li><code>Order</code> <strong>Has Many</strong> <code>Item</code>.</li>
</ul>

<p>So far so good.</p>

<p>Now I want to sum the price of the items that belongs to the orders that belongs to the coupon. So I thought about doing something like this:</p>

<pre><code>Coupon::orders-&gt;items-&gt;sum('price');
</code></pre>

<p>Well, it won't work because <code>orders()</code> method returns a <code>Collection</code> of the relation:</p>

<pre><code>/**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function orders()
{
    return $this-&gt;hasMany(Order::class);
}
</code></pre>

<p>I'm getting an error that says <code>item</code> property is protected. I found out that it doesn't related to my <code>Item</code> module, it's just because <code>Collection</code> has <code>protected $items = [];</code>.</p>

<p>So, after I cleared out some facts, my question/problem is, How can I sum the <code>items-&gt;price</code> of the <code>orders</code> that belong to <code>Coupon</code>?</p>

<hr>

<p>Of course I can achieve my goal by doing a foreach loop like this:</p>

<pre><code>$price = 0;

foreach (Coupon:orders as $order)
    $price += $order-&gt;items-&gt;sum('price');

return $price;
</code></pre>

<p>But I'm looking for a cleaner solution. Anyone?</p>