In this episode, we dive deep into the one of many
relationship modifier in Laravel, which is a handy tool for grabbing a single item out of a group of related models—think "the latest comment" or "the most liked comment" on an article. It's not its own relationship type but rather a modifier you can use to make your relationships much more focused and efficient.
First, we look at the classic example: how to show just the latest comment for each article, instead of loading up all comments and manually picking the first or last (which is both slow and memory-hungry). We set up a custom relationship using latestOfMany()
so you can access article->latestComment
just like any other relationship, and discuss the importance of eager loading to avoid the dreaded N+1 query problem.
Next, we flip things around and fetch the oldest comment using oldestOfMany()
, showing you how easy it is to swap modifiers and get exactly what you need from your relationships.
Finally, we get a little fancier and fetch the most liked comment by tweaking the database and using ofMany('likes', 'max')
, which returns the comment with the highest number of likes for each article. You’ll see how this pattern lets you create clear, focused relationships—and keeps your code readable and maintainable.
Throughout the episode, you’ll see practical code examples, some database tweaks, and tips on eager loading to keep your app speedy. By the end, you’ll be comfortable applying "of many" modifiers to tailor data fetching to your needs!