Fetch the data of parent model into static::saving() boot function

1.1k Views Asked by At

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?

1

There are 1 best solutions below

1
On

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');
}