0

i realized that "interest_amount" on my "loan" table is multi-valued attribute. so should i just create a table to split "loan" table or should i create a different model? i need different table for "interest" since i have to mark each month's interest as paid/unpaid.

i created a new model "InterestAmount" and table "interest_amounts" which has to be inserted automatically once a "loan" is inserted.

Loan('id','amount','interest_rate')
InterestAmounts('id','loan_id','interest_amount')

here interest_amount is value computed using 'amount' and 'interest'. and data in table interestamount has to be inserted automatically.

do i need to use event and listener for automatic entry??

  • 1
    no need. $loan = new Loan(blabla); $loan->save(); InterestAmount::insert(['loan_id' => $loan->id, 'interest_amount' => $loan->amount * $loan->interest_rate]); – Rizky Arlin Apr 25 '19 at 12:33
  • so a model is required.... where do it put this code, in InterrestAmountcontroller or LoanController? – Prithvi Tuladhar Apr 26 '19 at 05:48

1 Answers1

1

In Laravel, this can be solved by using one-to-many relationship. Here your one loan has multiple InterestAmounts.

So, you have to define two models,

One is Loan Model:

class Loan extends Model
{
  protected $table = 'Loan';

  public function interestAmounts()
  {
    return $this->hasMany(InterestAmount::class, 'loan_id');
  }
}

Another one is InterestAmount Model:

class InterestAmount extends()
{
  protected $table = 'InterestAmounts';

  public function loan()
  {
    return $this->belongsTo(Loan::class, 'loan_id');
  }
}

Now, if you want to insert InterestAmounts when an Loan has been inserted with proper calculation, you can do so as below:

To crate loan:

$loan = Loan::create([
  'amount' => $amountValue,
  'interest_rate => $interestRateValue,
]);

To add InterestAmounts with proper calculation:

$loan->interestAmounts()->create([
  'interest_amount' => $loan->amount * $loan->intrest_rate,
]);

Here, the loan_id will be added automatically. You can even do it manually:

InterestAmount::crate([
  'loan_id' => $loan->id,
  'interest_amount' => $loan->amount * $loan->intrest_rate,
]);
Imran
  • 4,582
  • 2
  • 18
  • 37