In this episode, we're tackling the first major step for our shopping cart system: creating a cart record in the database tied to a user's session. This is key because we want to let users add products to their cart whether they're logged in or not, and keep those carts persistent as they browse.
We start off by figuring out when and how to trigger cart creation. Instead of creating a cart in the controller, we move this logic into dedicated middleware for a cleaner setup. You'll see how to make custom middleware with Artisan, inject our cart interface via the constructor, and properly register it in the HTTP kernel so it runs on every web request.
Next up, we implement logic to check if a cart already exists for the user's session. We use the Laravel session manager for this, pulling out the session key from a new config/cart.php
config file for reusability. If the cart doesn't exist, we create a new cart model instance—optionally associating it with the user if they're logged in.
We also hook up a belongsTo
relationship from the cart to the user and ensure that a UUID is generated for each new cart. To avoid duplicating carts on every page load, we store the generated cart UUID in the session after creation, so subsequent requests will see the key and skip making a new cart.
We wrap up by testing both guest and logged-in user flows, making sure only one cart gets created per session. Plus, we chat about cleaning up expired carts (hint: you could use a scheduled job for that). With all this in place, we've got a solid cart session system ready for adding items next!