Skip to content
Advertisement

How to load a nested relationship in Laravel

I have a model called CallbackRequest the model has a relationship with Loan model and that is the only relationship for CallbackRequest model.

CallbackModel:

public function loan() {

    return $this->belongsTo(Loan::class);
}

Now Loan model itself has a relationship with a third model called Applicant.

Loan Model:

public function applicant() {

    return $this->belongsTo(Applicant::class);
} 

My point:

When I load CallbackRequest I eagerload loan model with it, all fine! But now I am wondering if there is a way to eagerload applicant model when I do:

Right now I access it like:

$modelResults = PublicCallback::with('loan')->get();

I get all callbacks with loan eagerloaded, but my point is I want when I eagerload loans in this case I want applicant to be loaded also !

Is there any way how to do this, is it possible ?

Advertisement

Answer

You can do this with:

$modelResults = PublicCallback::with(['loan', 'loan.applicant'])->get();

Ref: https://laravel.com/docs/5.5/eloquent-relationships#eager-loading

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement