Eager loading, but only if you really need to

Since we want to reduce the number of queries

Joel Clermont
Joel Clermont

The whole point of eager loading is to reduce the total number of queries needed to serve a request. But have you considered what happens if you eager load the same relationship more than once in a request?

Laravel will dutifully repeat the same eager loading query it already executed, which works against the whole reason we're eager loading in the first place.

As usual, Laravel gives an elegant solution, but before I share it, you might be wondering why you'd ever even try to eager load the same relationship more than once.

I'll be honest, it's not something I bump into a lot, but I can think of a couple scenarios where this could happen:

  1. Maybe you have some conditional logic around eager loading, and more than one condition could cause the same relationship to be eager loaded. Instead of trying to combine the conditionals and make the code less readable, you prefer to leave them in a flatter structure.

  2. You could be dealing with nested Livewire components and, depending on the context, you might already have some relationships eager loaded, but it's easy to lose track of this.

Regardless of the reason, the solution is the same: use the loadMissing method instead of load. It accepts an array of relationship names, but internally it first checks to see if each one is already eager loaded, and skips the extra query if it isn't actually needed.

Overall, my advice would be to try to avoid this situation in the first place, but if you do find yourself facing this problem, now you know how to handle it.

Here to help,


P.S. Does your Laravel app have some performance issues? Don't keep cranking up your server size. Let's figure out how to make your app faster instead.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.