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?
The
$model
variable insideInterestAmount
model refers to anInterestAmount
object :Then you need to get the related
loan
using your relationship methodloan()
then get the propertiesamount/interest
.NOTE: As @namelivia's comment says you're missing the
return
in theloan()
method: