In this episode, we're kicking off our journey into handling address records by focusing on the creation part. We start by setting up a new route in our Laravel app that's responsible for creating an address for a user. Even though a real application would typically use a POST request to save a new address, here we're using a GET route just to get comfortable with how it all works.
First, we make sure our chosen user doesn't already have any addresses, then we fetch this user from the database. The main technique demonstrated is creating a new address—the right way—by using the relationship method on the user model. This allows Laravel to automatically assign the address to the correct user without manually specifying user_id
.
We then run into a common Laravel gotcha: mass assignment protection. Laravel blocks mass assignment on models unless the fields are specified as fillable. We fix this by adding a $fillable
property to our Address model so that line_one
can be set.
Once that’s fixed, we see the address get created in our database, all properly linked to our user. The episode also covers alternative (and less recommended) methods, like manually creating an address by specifying the user_id
, making user_id
fillable, or using forceCreate
to bypass fillable protections. The takeaway is clear: whenever you’re working with related models, the cleanest, safest way is always through the relationship methods.
By the end, we've not only created an address and learned a bit about Laravel's mass assignment security, but we've also peeked at various ways to link related records—and learned which are best to use in the real world.