Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple level eager loading in Laravel?

Let's say I have these relationships

class Invitation
{
    public function invitedPeople()
    {
        return $this->belongsTo('App\Person', 'personID');
    }
}

class Person 
{
    public function apartments()
    {
        return $this->belongsToMany('App\Apartment', 'apartment_person', 'personID', 'apartmentID');        
    }
}

class Apartment 
{
    public function city()
    {
        return $this->belongsTo('App\City', 'cityID');
    }
}

My question here is, how many nested levels can we have when using Laravel eager loading? I've tried this query and it's not working, can someone suggest a work around for this?

return Invitation::with(['invitedPeople', 'invitedPeople.apartments', 'invitedPeople.apartments.city'])
like image 569
Luis Deras Avatar asked Mar 17 '16 19:03

Luis Deras


1 Answers

Change it to

 return Invitation::with('invitedPeople.apartments.city')->get()

It will eager load all the related data for you. You missed the get() function. You can nest as deep as it can go.

like image 59
oseintow Avatar answered Sep 20 '22 23:09

oseintow