In this episode, we're starting the process of getting our shopping cart functionality up and running. The very first thing we tackle is deciding how and where to store the items that users add to their cart. An important consideration is that our cart needs to work for both signed-in users and guests, so we plan for that from the outset.
We begin by creating a Cart
model and a corresponding database migration. In this migration, we add a nullable user_id
field—since guests won't have a user ID—and a UUID that uniquely identifies each cart session. We discuss why a UUID is useful: it allows us to track cart sessions even if a user isn't authenticated. We run the migration, confirm our cart table is created, and explain how new carts are generated and associated either with sessions (for guests) or user accounts (once users sign in).
Next, we think about how to store the actual items in the cart. To do this, we set up a pivot table called cart_variation
. This table connects the cart itself with variations of products (like size or color), and also keeps track of the quantity for each variation. The fields here are a foreign key for the cart, a foreign key for the variation, and the quantity. We migrate this table and check it out in the database.
By the end of the episode, our database schema is ready to store cart sessions and their contents. We've paved the way for handling both guests and authenticated users, and set things up so we can easily calculate cart totals in the future. Next up: we'll focus on creating the cart service and fetching the cart as users browse the site.