Laravel — Nested Eager Loading Contraints

Sander
2 min readOct 3, 2018

--

Hi there!

We recently encountered some challenges while working on one of our applications. We tried to eager load a specific set of data while specifying additional query constraints, multiple relations deep. We soon discovered this was something that wasn’t documented nor easily to find.

TL;DR: layer your eager loading constraints to ensure all your nested relationships along the way are constrained as well.

Our use-case is as follows. A user is part of a team, which has some portfolios. Within these portfolios, the user and the team both own a wallet that contains some transactions. A transaction could be originated from the team to a user, the other way around or user to user. We were looking for a way to eager load all teams where the given user owns a wallet within a team’s portfolio that contains pending received transactions. Top down, using a single query.

So we looked at the documentation example about constraining eager loads.

The example explains how to constrain a query on a nearby relationship. However, if we were to use the dot notation to load relationships far away, the constrain wouldn’t be used for all relations. Furthermore, the model retrieval (in our case Team) won’t be constrained at all.

To solve this problem, we need to layer your eager loading constraints. By doing so, our constraints will be used for all relations:

So now we got the data we need from all teams. But we only need teams that have the right data. To do so, we will use another whereHas() to constrain the query a little more:

So there you have it, nested eager loading constraints using a single query! 😊

Since you made it this far, you may want to hire us to solve your technical challenges! Take a look at our brand new website or the application where we encountered this challenge.

--

--