title: Laravel: Summing an attribute in a nested relation
body: <p>I want to sum a nested collection.</p>
  
  <p>I have the following tables:</p>
  
  <ul>
  <li>Venues</li>
  <li>Offers</li>
  <li>Orders</li>
  </ul>
  
  <p>A <code>venue</code> can have many <code>offers</code> and a <code>offer</code> can have many <code>orders</code>.</p>
  
  <p>Example data may be:</p>
  
  <p><strong>Venues</strong></p>
  
  <pre><code>id        |  name
  ==========================
  5         |  Pizza 4 Less
  10        |  Poundland
  </code></pre>
  
  <p><strong>Offers</strong></p>
  
  <pre><code>id | venue_id | name
  ==================================
  17 | 5        | Buy 1 get one free 
  24 | 5        | 30% off pizza
  32 | 10       | 50% off
  50 | 10       | 20% off
  </code></pre>
  
  <p><strong>Orders</strong></p>
  
  <pre><code>id | offer_id | bill | paid
  ===========================
  85 | 17       | 15   | true
  86 | 17       | 20   | true
  87 | 17       | 90   | true
  88 | 24       | 14   | true
  89 | 32       | 15   | true
  90 | 32       | 65   | true
  91 | 50       | 24   | true
  92 | 50       | 1000 | false
  </code></pre>
  
  <p>I want to use Laravel Elqouent model to get the total amount paid for each venue. So for the above data I want to get the following result:</p>
  
  <pre><code>id | name          | total_paid
  ===============================
  5  | Pizza 4 Less  | 139
  10 | Poundland     | 104
  </code></pre>
  
  <p>Note that the totals did not include orders that was not paid (i.e. order 92)</p>
  
  <p>The way I currently do this is as follows:</p>
  
  <pre><code>$venues = Venue::with(['offers.orders' =&gt; function ($query) {
          $query-&gt;where('paid', '=', true);
      }])
      -&gt;get();
  
  $totals = [];
  foreach ($venues as $venue) {
      $totalPaid = 0;
      foreach ($venue-&gt;offers as $offer) {
          $totalPaid += $offer-&gt;orders-&gt;sum('bill');
      }
      $totals[$venue-&gt;name] = $totalPaid;
  }
  </code></pre>
  
  <p>As you can see, the above code is inefficient and long. </p>
  
  <p>Is there a better way to do this?</p>