In this episode, we dig into Laravel's hasOneThrough
relationship and see how it works a bit differently than the more common hasManyThrough
. We tackle a practical scenario: users have many referral codes, referrals reference those codes, but do NOT directly reference users. This means if we want to fetch the user for a referral, we have to get them through the referral code. (If that sounds roundabout, it is! But it's great for learning weird database relationships.)
We start by setting up our models—Users, Referral Codes, and Referrals—and fill the tables with some test data using factories and manual entry. You'll see how to wire up migrations so that referral codes belong to users and referrals belong to referral codes (without referring to users directly!).
Next, we create an admin view to list all referrals and display their associated user and referral code. This is where it gets interesting: since the user isn't directly on the referral, accessing their details means working out a hasOneThrough
relationship. We experiment with the keys and show some trial-and-error, so you'll see how to map the right foreign/local key combinations to make Laravel happy.
Once that's working, we check out eager loading—fixing the dreaded N+1 query problem that could slow down our app. You'll learn how to eager load both the referral code and user relationships, even when they're accessed through intermediate models.
We also touch on alternative approaches and discuss code readability: while you can navigate multiple relationships the “long way” (referral ➡️ code ➡️ user), sometimes setting up a hasOneThrough
makes your code cleaner and easier to work with.
By the end, you'll understand why and when you might use hasOneThrough
, how to set it up, and a few practical tips to make your relationships efficient and maintainable.