How to add data from a foreach?

1

I have a question, how can I add the values of the foreach? In this case I want to add the sales, to be able to show the total sales that the assignments have.

One assignment can have many sales.

<tbody>
  <?php $numero = 0; ?>
  @foreach ($asignaciones as $asignacion)
  <tr>
      <td>{{ $numero = $numero +1 }}</td>
      <td>{{ $asignacion->fecha }}</td>
      <td>{{ $asignacion->user->nombre }}</td>
      <td>{{ count($asignacion->ventas) }}</td>
  </tr>

  @endforeach
</tbody>
<thead>
  <tr>
      <th width="20px">Total</th>
      <th></th>
      <th></th>
      <th>?</th>
  </tr>
</thead>

    
asked by Jhosselin Giménez 09.03.2017 в 02:17
source

1 answer

1
<?php $numero = 0; $total = 0;
?>
  @foreach ($asignaciones as $asignacion)
  @php 
     $cantidad=count($asignacion->ventas);
     $total+=$cantidad;
  @endphp
  <tr>
      <td>{{ $numero = $numero +1 }}</td>
      <td>{{ $asignacion->fecha }}</td>
      <td>{{ $asignacion->user->nombre }}</td>
      <td>{{ $cantidad) }}</td>
  </tr>
  @endforeach
</tbody>
<thead>
  <tr>
      <th width="20px">{{$total}}</th>
      <th></th>
      <th></th>
      <th>?</th>
  </tr>
</thead>

cove with this, (I have not tried it, sure there is more than one error out there.)

Now, it is not advisable and in fact you could say that it is bad practice to code the logic within a view (come the quantity and the total) what you could do is create a small, testable method in your model that give you the arrangement with all the values ready to print. (A serious advantage if you want to add more elements, you will not have to agglutinate all your code in this file that is supposed to be dedicated to print the information).

    
answered by 09.03.2017 в 08:37