In this episode, we dive into setting up and seeding our nested category data for the app. We kick off by building a seeder for our categories, making it easy to get the database filled with lots of example data. Starting with just a simple root category, like "Shoes", we use Laravel's factories to generate these records, and then run the seeder to make sure it all lands in the database as expected.
Next, we talk about wiping the existing category records each time the seeder runs so we always start fresh, and then we apply a special trait to our Category model from the package we're using. This trait automatically wires up useful relationships, like children
, ancestors
, and descendants
, making it super easy to work with nested categories later on.
The main part of the episode is about how you actually set up these nested categories using factories and the has
relationship method. We show how to build a "Shoes" category, then add a child category like "Boots", and even go further by nesting another level inside (for example, "New In" under "Boots"). There's a quick fix on making sure you're using the right relationship name so your subcategories connect properly.
We repeat the process a couple of times to seed more complex structure, like adding root categories for "Jackets" with subcategories like "Outdoor" or "Winter", and make sure the slugs are unique. Once we've got enough data in the database, we head over to the controller and frontend to display these categories. First, we fetch all categories and show them, then we tweak the query to just grab the root categories ("Shoes" and "Jackets"), setting us up for building a nested tree in the UI next.
By the end, we've got a seeded and ready-to-use set of nested categories, perfect for building out more features!