In this episode, we're diving into a cool new update to Laravel's Eloquent relationships, specifically around the HasOneThrough
and HasManyThrough
relationships. If you've ever found yourself needing to grab a single related model (like the latest of many) through another relationship, things just got a lot easier!
We kick things off with a quick refresher on how HasManyThrough
works. Using a practical example, we look at a setup where a User has many Projects, and each Project has many Deployments. Traditionally, if you wanted to get all deployments for a user, regardless of project, you'd use a HasManyThrough
relationship.
But what if you only want, say, the latest deployment for each user? The video walks through how you might try to solve this before, like grabbing all deployments and then plucking the latest one, but that can get pretty inefficient (hello, N+1 queries!).
Here's where the new magic happens: Laravel now supports the ofMany
extension for HasOneThrough
, letting you easily fetch, for example, the latest deployment through the user's projects, all in one clean, efficient query. The episode shows how you can use methods like latestOfMany
to make your code both faster and more expressive.
If you're working with more complex relationships or just want to keep your Eloquent code tidy and efficient, this one's a must-watch! Plus, there's a GitHub example you can follow along with and apply to your own projects.