title: Laravel - how to calculate the sum of objects in an array in blade view
body: <p>I have a foreach loop in a blade view, where I am listing the objects that have a pivot property price:</p>
  
  <pre><code>                @foreach($transaction-&gt;options as $option)
                    &lt;div class="row"&gt;
                      &lt;div class="col-md-6"&gt;
                        &lt;p&gt;Option description: {{ $option-&gt;description }}&lt;/p&gt;
                        &lt;p&gt;Price: {{ $option-&gt;pivot-&gt;price }}&lt;/p&gt;
                      &lt;/div&gt;
                    &lt;/div&gt;
                    &lt;hr&gt;
                  @endforeach
                  &lt;div class="row"&gt;
                    &lt;div class="col-md-6"&gt;
                      &lt;h4&gt;Options total: &lt;/h4&gt;
                    &lt;/div&gt;
                  &lt;/div&gt;
  </code></pre>
  
  <p>I would like to since I am doing a foreach loop here, calculate the sum of all the options so that I could write it next to <code>Options total:</code> </p>
  
  <p>I have tried with this:</p>
  
  <pre><code>               @foreach($transaction-&gt;options as $option)
                    &lt;div class="row"&gt;
                      &lt;div class="col-md-6"&gt;
                        &lt;p&gt;Option description: {{ $option-&gt;description }}&lt;/p&gt;
                        &lt;p&gt;Price: {{ $option-&gt;pivot-&gt;price }}&lt;/p&gt;
                        @php($total += $option-&gt;pivot-&gt;price)
                      &lt;/div&gt;
                    &lt;/div&gt;
                    &lt;hr&gt;
                  @endforeach
                  &lt;div class="row"&gt;
                    &lt;div class="col-md-6"&gt;
                      &lt;h4&gt;Options total: {{ $total }}&lt;/h4&gt;
                    &lt;/div&gt;
                  &lt;/div&gt;
  </code></pre>
  
  <p>But, that didn't work, I got an error:</p>
  
  <blockquote>
    <p>Undefined variable: total</p>
  </blockquote>
  
  <p>How can I do this?</p>