简体   繁体   中英

How to get the sum of values in a table column in laravel

I have the below table in a Laravel blade file, which renders data.

For each column I would like to get the total value and display a total at the bottom so I don't have to added each row manually.

What would be the best way of doing this as I seem to be hitting walls and can't find anything to assist online.

Lets say you want sum of products price. In your controller where you retrieve products, for example:

$products = Product::where('status', '=', 'active')->get();

You can also get the sum using:

$totalPrice = Product::where('status', '=', 'active')->sum('price');

and use this variable in your blade template.

Add another row to your blade file like this:

<tr>
  <td nowrap style="overflow: hidden;">{{$name}}</td>
    @foreach($months as $month)
      <td>{{'£'.array_reduce($products, function ($previous, $product) use ($month) {
          $value = $product['current']->has($month->format('m/Y')) ? intval($product['current'][$month->format('m/Y')]->sum('batch_total')) : 0;
          return $previous + $value;
      }, 0)}}</td>
    @endforeach
      <td>{{'£'.array_reduce($products, function ($previous, $product) {
          return $previous + intval($product['on_hold']['total']);
      }, 0);}}</td>
      <td>{{'£'.array_reduce($products, function ($previous, $product) {
          return $previous + intval($product['current']->flatten()->sum('batch_total') + $product['on_hold']['total']);
      }, 0);}}</td>
      <td>{{array_reduce($products, function ($previous, $product) {
          return $previous + intval($product['last_year']->flatten()->sum('batch_total'));
      }, 0);}}</td>
</tr>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM