In this episode, we dive into how you can use aggregate functions in your Eloquent relationships. Specifically, we look at how to get a user's most upvoted (or most 'voted for') post with a neat and efficient query—no messy collection manipulation required!
We start by adding a new votes
column to our posts
table and updating some test data. After that, we move on to setting up a new route and creating a practice endpoint that fetches and displays the user's top-voted post. Instead of looping through posts or writing manual queries, we take advantage of Eloquent's has one of many
relationship with aggregated functions (like max()
for the highest number of votes).
You'll learn how to set up a custom relationship on the User model using the ofMany
method. We use max
as the aggregate function and show that this approach is both memory efficient and very readable. To finish up, you'll see how this technique can be adapted to get other extremes, such as the most expensive item, or really anything based on a min/max column value.
By the end, you'll understand how to fetch "the one of many" using aggregate functions, making your code simpler and faster!