In this episode, we're setting up the main Cart service for our e-commerce app. Instead of just using a simple model, we're creating a dedicated Cart class that will handle all cart-related logic and operations. The idea is to keep this service separate from our Cart model for better organization and flexibility.
We walk through structuring our folders, creating a Cart
class and its matching interface (CartInterface
). Even though the interface doesn't have any methods just yet, it makes it easy to bind things together using Laravel's service container, which is great for dependency injection down the line.
Next, we register our Cart service by making a custom CartServiceProvider
. This lets us "bind" our Cart implementation to the interface, so we can inject it anywhere we want—like controllers or Livewire components—with minimal fuss. We show both constructor injection and using the app()
helper to resolve the service.
Since our cart's data will live in the session (for now), we update the class to accept Laravel's Session Manager. We make sure the service provider provides the session, and check that everything is being passed in correctly. There's a quick die-and-dump check to see it working in action.
By the end, we've got a reusable, injectable Cart service set up and ready to talk to the session. In the next part, we'll focus on actually creating a cart in the database and tying it to the session data, so the cart persists for our users!