In this episode, we're focusing on how to save a shipping address after a user completes an order. The goal is to make the checkout experience smoother for next time by letting users quickly reuse previously entered addresses.
We start by discussing why we need to store shipping addresses and what some of the important considerations are—like making sure we don’t save addresses for unauthenticated users, and avoiding duplicate addresses (no one wants A, B, and C turning up multiple times!).
Next, we jump into creating a ShippingAddress
model and migration in the database, sketching out the fields we need (user, address, city, postcode, etc.). We also make sure the user field can be nullable for guest checkouts.
We then set up Eloquent relationships on both the User
and ShippingAddress
models so users can have multiple addresses, and each address can optionally belong to a user.
To avoid duplicates, we use the handy firstOrCreate
method when saving new addresses, ensuring each one is unique per user. We then demo saving addresses both as a guest and as a signed-in user, including assigning addresses to the correct user.
Finally, we work through a tricky edge case where two users might save the same address, and make sure each user gets their own entry so we don’t accidentally assign a shipping address from one user to another.
By the end of the episode, you’ll have a robust start to saving and managing user shipping addresses in your app, ready to build on for future features like easily selecting from pre-saved options at checkout.