title: Laravel Eloquent: Best Way to Calculate Total Price
body: <p>Im building a simple buy and sell application with Laravel 5.1. Each Buy Model has many BuyDetail which stores bought item quantity and buy_price. I have implement the relationship between table on the Model.</p>
  
  <pre><code>class Buy extends Model
  {
    #Eloquent relationships
  
    public function supplier()
    {
      return $this-&gt;belongsTo('App\Supplier');
    }
  
    public function buyDetails()
    {
      return $this-&gt;hasMany('App\BuyDetail');
    }
  }
  </code></pre>
  
  <p>I'd like to calculate the total price for each Buy. What is the best way to calculate the total price using Eloquent ORM?</p>
  
  <p>for now i just implement it like this:</p>
  
  <pre><code>@foreach($buys as $key =&gt; $value)
      &lt;?php
          $total = 0;
      ?&gt;
      @foreach($value-&gt;buyDetails as $k =&gt; $bD)
          &lt;?php
              $total += ($bD['buy_price']*$bD['qty']);
      ?&gt;
      @endforeach
  
     &lt;tr&gt;
      &lt;td&gt;{{$value-&gt;ref_number}}&lt;/td&gt;
      &lt;td&gt;{{$value-&gt;suplier-&gt;name}}&lt;/td&gt;
      &lt;td&gt;{{$value-&gt;created_at}}&lt;/td&gt;
      &lt;td&gt;{{$value-&gt;buyDetails-&gt;count()}}&lt;/td&gt;
      &lt;td&gt;{{$total}}&lt;/td&gt;
      &lt;td&gt;
          &lt;a href="" class="btn btn-default btn-sm" title="show"&gt;Detail&lt;/a&gt;
          &lt;a href="" class="btn btn-primary btn-sm" title="edit"&gt;Edit&lt;/a&gt;
          &lt;a href="" class="btn btn-danger btn-sm" title="delete"&gt;Delete&lt;/a&gt;
      &lt;/td&gt;
    &lt;/tr&gt;
  @endforeach
  </code></pre>