Leff7
1 year ago
155
7
Laravel

Laravel - how to calculate the sum of objects in an array in blade view

Posted 1 year ago by Leff7

I have a foreach loop in a blade view, where I am listing the objects that have a pivot property price:

                @foreach($transaction->options as $option)
                  <div class="row">
                    <div class="col-md-6">
                      <p>Option description: {{ $option->description }}</p>
                      <p>Price: {{ $option->pivot->price }}</p>
                    </div>
                  </div>
                  <hr>
                @endforeach
                <div class="row">
                  <div class="col-md-6">
                    <h4>Options total: </h4>
                  </div>
                </div>

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 Options total:

I have tried with this:

               @foreach($transaction->options as $option)
                  <div class="row">
                    <div class="col-md-6">
                      <p>Option description: {{ $option->description }}</p>
                      <p>Price: {{ $option->pivot->price }}</p>
                      @php($total += $option->pivot->price)
                    </div>
                  </div>
                  <hr>
                @endforeach
                <div class="row">
                  <div class="col-md-6">
                    <h4>Options total: {{ $total }}</h4>
                  </div>
                </div>

But, that didn't work, I got an error:

Undefined variable: total

How can I do this?

Please sign in or create an account to participate in this conversation.