1

I want to use data from the parent model to run the saving() function in the child model

Previously, I inserted a computed data to the table in model "Loan" but now I need to insert it into a child model "InterestAmount"

Loan.php

use Illuminate\Database\Eloquent\Model;
class Loan extends Model
{

    protected $fillable ['amount','interest','status','duration','member_id','loan_type_id','interest_type_id','loan_payment_type_id'];

    //protected $appends = 'interest_amount

    protected static function boot()
    {
        parent::boot();
        static::saving(function($model) {
            $model->interest_amount = ($model->amount/100 )* $model->interest;
        });
    }

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

}

I want to remove the saving function from Loan.php and use as below.

Interest.php

use Illuminate\Database\Eloquent\Model;
class InterestAmount extends Model
{
    public function loan()
    {
        $this->belongsTo(Loan::class,'loan_id','id');
    }

    protected static function boot()
    {
        parent::boot();
        static::saving(function($model) {
            $model->interest_amount = ($model->amount/100 )* $model->interest;
        }); 
    }
}

How do I fetch "amount" and "interest" in this function?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101

1 Answers1

1

The $model variable inside InterestAmount model refers to an InterestAmount object :

static::saving(function($model){
    $model->interest_amount = ($model->loan->amount/100 )* $model->loan->interest;
}); 

Then you need to get the related loan using your relationship method loan() then get the properties amount/interest.

NOTE: As @namelivia's comment says you're missing the return in the loan() method:

public function loan()
{
    return $this->belongsTo(Loan::class,'loan_id','id');
}
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • more importantly.. data in table "interest_amounts" needs to be inserted automatically once loan data is inserted since i split table "loan" as "interest_amount" to insert "interest amount" which is a multi valued attribute. can i get some help?? i was thinking of using event and listener but i have no idea how. – Prithvi Tuladhar Apr 23 '19 at 10:29