In the past, I've shared a video and a written article about using loadMissing to avoid duplicate eager loading queries.
Today, I want to follow up and add some additional nuance to this solution. You may end up deciding to reload those relationships if this applies to your code.
Consider this scenario: somewhere early in a request, you eager load a user's posts with a constraint.
$userWithRecentPosts = User::with(['posts' => function ($query) {
$query->where('created_at', '>=', Carbon::now()->subWeek());
}])->get();
Later in the same request, maybe in a different component or service, you need this same relationship, but you want all of their posts, not just the most recent ones.
If you use the loadMissing solution from the previous tips, you've eliminated the extra query, but you have a new problem now.
Your relationship is still filtered, which is not what you want.
You saved the query, but lost some relevant data.
The loadMissing method only checks whether the relationship key exists.
It doesn't keep track of whether it was filtered or not.
So in this case, you may actually want to avoid the optimization of loadMissing and stick with the basic load method instead.
Yes, this means an extra query, but it's a necessary query to satisfy your business logic.
Here to help,
Joel
P.S. Subtle bugs like this are hard to catch on your own. A fresh set of eyes can spot the issues you'd never think to look for. Schedule a code review.