In this episode, we tackle how to efficiently grab the latest post for a discussion in Laravel, and introduce the powerful has one of many
relationship.
First, we start by showing the old way of doing things: using the standard hasMany
relationship to get all posts for a discussion, and then in our template, picking out the latest post by sorting and picking the first one. We point out why this isn't a great idea—apart from mixing logic in your Blade templates, it results in extra queries and loads unnecessary data into memory.
Next, we move the logic to the model to tidy things up, showing how you might write a custom method to get the latest post. It's better, but still not ideal—especially if you want to eager-load related models like the post's author, or if you have large amounts of data.
Then, we introduce Laravel's has one of many
relationship, specifically the latestOfMany()
method. This lets us set up a relationship directly on the model to always get the latest related post, all in a single query, and you can eager-load it just like any other relationship. We demo how this works, and show that it keeps our queries super efficient regardless of how many posts or discussions you have.
Finally, we go back and compare the approaches to show just how much simpler and more performant it is to use relationships correctly, and why handling things at the database level is usually preferred. The has one of many
relationship really cleans up our code and makes things work exactly as you'd expect!