In this episode, we tackle the process of generating unique referral codes in Laravel—and make sure that the codes are actually unique so users don't run into random errors!
We start by reminding ourselves that even though our database schema enforces the uniqueness of referral codes, there's still a (tiny!) risk of generating a duplicate code when we create them randomly. To avoid this, we set up an Eloquent Observer for our ReferralCode model. This lets us automatically handle the code generation every time a new referral code is created, regardless of where the creation happens in our app.
From there, we refactor by moving the actual code generation logic into a simple ReferralCodeGenerator
class. This class takes care of creating a random string and making sure that string doesn’t exist in the database already. If, by chance, it does, it keeps generating a new one until it finds one that’s unique. Pretty handy, and it keeps our Observer nice and tidy!
Finally, we hook up the User model with its own Observer so a referral code gets created whenever a new user signs up. This approach ensures the logic is global—you don't have to remember to generate a code in every part of your app. By the end of this episode, you’ll have a rock-solid way to guarantee every user has a truly unique referral code automatically.