In this episode, we tackle a common confusion with Eloquent's one-to-one relationships in Laravel—specifically, how they're not as strict as you might expect. We see that if you run the address create route multiple times, you end up with multiple address records for the same user! So, even though it's a one-to-one relationship, Eloquent doesn't stop you from attaching more than one address to a user.
We investigate how the relationship only returns one record, but the database might actually store several. Most of the time, you'll probably want to use a one-to-many relationship since that's more flexible, but it's still good to understand what's going on behind the scenes.
Next, we explore how to always retrieve the most recent address for the user. We learn about the latest()
relationship modifier in Laravel and how to apply it so you always get the newest address attached to a user, even if there are multiple in the database. We try it out, see what happens, and then refine things by adding the scope directly to the user model relationship, so it's automatic.
By the end of this episode, you'll know how to deal with multiple related records in a "one-to-one" setup, and ensure your code always grabs the most relevant (i.e. newest) one. This is a must-know trick for anyone working with relationships in Laravel!