In this episode, we explore how you can switch up the key names used in your Eloquent relationships, which comes in handy if your database doesn't use Laravel's default conventions.
Usually, Laravel expects keys like user_id
for foreign keys and id
for primary keys. But sometimes, maybe your database uses different names—maybe you're working with a legacy database or you just have your own conventions. We'll go into our database and manually mess around with the key names (changing user_id
to something like person_id
for example) and see what impact that has. Spoiler: things break initially because Laravel can't find the right keys!
But don't worry, we fix it by explicitly telling Laravel what the new foreign key is, and show how you can also specify a custom owner key. There's even a quick example where both foreign and primary keys get custom names, and we see how to make it all work again.
We wrap up by talking about why it's generally a good idea to stick to Laravel's defaults unless you have a specific reason not to—but now you know exactly what to do if you ever need to change them.