In this episode, we dive right into setting up categories for our Laravel project by integrating the Laravel adjacency list package. This is a super helpful tool for working with nested categories (and later, product variations). If you haven't worked with adjacency lists before, don't worry—by the end, it'll make sense!
We start by tweaking our homepage so it can display categories instead of the default welcome screen. There are a few issues to fix first: the navigation expects a logged-in user, so we update our Blade components to only show certain menu options when someone is authenticated. This lets guests view our homepage without running into errors.
Next, we make a new Category
model and set up its migration with basic fields like title
, slug
, and a nullable parent_id
so we can support nested categories. We add a couple of top-level categories to the database and hook things up with a HomeController
that fetches categories and passes them to our new home view.
But just listing categories isn't enough—we want to show them as a nested tree! That's where the adjacency list package comes in. We pull it in with Composer, add the needed trait to our Category model, and add some subcategories to our database. Now, with a single query using the package's toTree
method, we can get all categories in a proper hierarchical format.
By the end of this episode, we've got everything set up to display categories in a tree structure—ready to be expanded further. In the next episode, we'll look at how to actually render this in our Blade templates. Stay tuned!