Home > front end >  How to sum table row data in laravel 8
How to sum table row data in laravel 8

Time:03-10

I want to sum up the data in my table. Please tell, How can I do it. I have tried the below method but it is not working.

enter image description here

This is my controller code

public function CreateRentCertificateReport(Request $request)
    {
        $data['reports'] = Report::distric()->status(1)->get();
        return view('adc.reports.start-create-report', $data);
    }

This is my view code

 <tbody>
@foreach($reports as $data)
<tr>
<td>{{$data->upazila->upazila_name}}</td>
<td >{{$data->column_one}}</td>
</tr>
@endforeach

<tr>
<td>Total</td>
@foreach($reports as $data)
<td>{{$data['column_one']->countBy()}}</td>
@endforeach  
</tr>
</tbody>

CodePudding user response:

Maybe by doing something like this:

@php
  $total = 0;
  foreach($reports as $report) {
    $total  = $report['column_one']
  }
@endphp

<tbody>
  @foreach($reports as $report)
    <tr>
      <td>{{$report->upazila->upazila_name}}</td>
      <td >{{$report->column_one}}</td>
    </tr>
  @endforeach
  <tr>
    <td>Total</td>
    <td>{{$total}}</td>
  </tr>
</tbody>

CodePudding user response:

You can use pluck() and sum() :

<tbody>

    @foreach($reports as $data)
    <tr>
        <td>{{ $data->upazila->upazila_name }}</td>
        <td >{{ $data->column_one }}</td>
    </tr>
    @endforeach

    <tr>
        <td>Total</td>
        <td>{{ $reports->pluck('column_one')->sum() }}</td>
    </tr>

</tbody>

CodePudding user response:

Instead of calling ->get() on an Eloquent query, you can call ->sum(“column_name”) to get a number which is the sum of that column’s values

  • Related