Sitemap
Muhammad Azeem (Full-Stack Developer)

Muhammad Azeem (Full-Stack Developer)

Muhammad Azeem is a full-stack developer specializing in PHP, Laravel, React, and ML integration. He loves hackathons, tech trends, hiking, and cycling.

Member-only story

Stop `N+1` for Polymorphic Relations: Laravel’s `morphTo` and `loadMorph` for Efficient Eager Loading

--

Press enter or click to view image in full size

It was a Tuesday afternoon, and our new ‘Activity Feed’ dashboard was live. Stakeholders loved it. The problem? My Sentry alerts were screaming. Thousands of duplicate database queries, all hitting the posts and videos tables, cascading from a single endpoint that was barely getting any traffic. The feed showed recent user comments, and each comment could belong to either a post or a video. What worked fine in dev with a few dozen comments was utterly choking production with thousands.

The Hook & The Headache

The application wasn’t just slow; it was failing under load, forcing retries and degrading the user experience. Digging into the logs, the pattern was clear: for every Comment retrieved, a separate query was being executed to fetch its associated Post or Video. This wasn't a general N+1 issue I’d overlooked; this was specifically a polymorphic N+1 problem, insidious because the traditional with() method doesn't quite cut it here.

The Flawed Approach

The initial instinct, and frankly, what many developers reach for, is a simple with('commentable') on the Comment model. Or worse, iterating through the comments collection and manually calling…

--

--

Muhammad Azeem (Full-Stack Developer)
Muhammad Azeem (Full-Stack Developer)

Written by Muhammad Azeem (Full-Stack Developer)

Muhammad Azeem is a full-stack developer specializing in PHP, Laravel, React, and ML integration. He loves hackathons, tech trends, hiking, and cycling.