Skip to content
Advertisement

How to calculate balance when the records I want to show in desc order?

I want to to show the recently created amount at the top but also I want to show the balance column, the balance column will add or subtract the amount from the record

Controller

$ledgerTransactions = LedgerRecord::where('ledger_id', $id)->orderBy('created_at', 'asc')->get();

Blade

@php
  $balance = 0;
  $ledgerTransactions = $ledgerTransactions->map(function($transaction) use(&$balance) {
    $transaction->total = $transaction->sum('amount');
    if ($transaction->type == "Payment") {
      $transaction->total *= -1;
    }
    $transaction->balance = ($balance += $transaction->total);
    return $transaction;
  })->reverse();
@endphp

@foreach($ledgerTransactions as $transaction)
    <tr>
        <td>
            <p class="mb-0">{{ $transaction->created_at->format('M d, Y') }}</p>
        </td>
        <td class="font-weight-bold">{{ $transaction->type }}</td>
        <td>{{ $transaction->description ?? '' }}</td>
        <td>
            ${{ $transaction->amount }}
        </td>
        <td>
            ${{ $transaction->balance }}
        </td>
    </tr>
@endforeach

The problem with this is it starts adding from top, which I don’t want. I want it starts adding from bottom

Expected results are marked in red color in below image

enter image description here

Advertisement

Answer

It’s probably something as easy as this:

@php
  $balance = 0;
  $ledgerTransactions = $ledgerTransactions->map(function($transaction) use(&$balance) {
    $transaction->total = $transaction->amount;
    if ($transaction->type == "Payment") {
      $transaction->total *= -1;
    }
    $transaction->balance = ($balance += $transaction->total);
    return $transaction;
  })->reverse();
@endphp

@foreach($ledgerTransactions as $transaction)
    <tr>
        <td>
            <p class="mb-0">{{ $transaction->created_at->format('M d, Y') }}</p>
        </td>
        <td class="font-weight-bold">{{ $transaction->type }}</td>
        <td>{{ $transaction->description ?? '' }}</td>
        <td>
            ${{ $transaction->amount }}
        </td>
        <td>
            ${{ $transaction->balance }}
        </td>
    </tr>
@endforeach
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement