In this episode, we dive into modeling and accessing a simple one-to-one relationship in Laravel. The main example we use is having a User
model that can have one and only one Address
. We start with a brand new Laravel project and walk through setting up the database connection and running the initial migrations.
Next, we generate an Address
model and accompanying migration using artisan commands. We update the new migration file to link the address to a user via a user_id
foreign key, and we add a simple property for the address itself (though you can add as many address fields as you need in reality). After updating the migration, we run it to create the addresses
table in our database.
With the database in place, we go over defining the actual one-to-one relationship. In the User
model, we add a method called address()
that returns a hasOne
relationship with the Address
model. We cover how to import models if they're in different namespaces and explain some important Laravel conventions for relationships.
Afterward, we seed the database with a fake user by using Laravel's built-in model factories and Tinker, making it easy to test without setting up a whole registration system. We then create an address record manually for our fake user to demonstrate the relationship.
Finally, we set up a web route and a simple view to pull out a user and their address, showing how to access the relationship in a Blade template. We talk about handling cases where a user might not yet have an address (i.e., the relationship is null) and ways to safely access relationship data inside the template.
By the end of the episode, you'll have seen the full process of building, defining, and displaying a one-to-one relationship in Laravel, with plenty of tips and best practices along the way!