Search code examples
laraveleloquenteloquent-relationshiplaravel-controllerlaravel-models

How to show bank balance through transactions in laravel


I have Bank table and transaction table. The relationship is one-to-many, so a bank may have many transactions. Transaction table has the bank foreign key(bank_id). and each transaction has a column 'type' which is either credit or debit. I want to show each bank balance based on its transactions.

Here are my questions:

  1. How to select a specific bank?
  2. How to calculate the balance for a bank?
  3. Should I calculate it in controller, model, or view? which one is the best?

Here is transactions table: enter image description here thanks in advance!


Solution

  • I'm not sure what you are trying to do. You'd select a bank like

    $bank = Bank::find(2);
    

    and you could do something like

    $bank->transactions->sum('amount');