Avoid N+1 Query Problems in Laravel Using loadMissing()
The Hidden Problem: Duplicate Relationship Queries
In Laravel applications, relationships are often loaded in multiple places.
Example:
- Controller loads
user - Later, a service loads
user->roles - A resource loads it again
This can lead to extra database queries.
The Smart Solution: loadMissing()
Laravel provides loadMissing() to load a relationship only if it hasn't been loaded already.
Example:
$user->loadMissing('roles');
If roles is already loaded → nothing happens.
If not → Laravel loads it.
Why This Is Useful
loadMissing() helps you:
- Avoid duplicate queries
- Write reusable services
- Prevent N+1 query problems
- Keep performance predictable