In this episode, we're tackling how to handle categories that can go multiple levels deep—think parent, child, grandchild, etc.—without causing a mess of database queries. Instead of trying to eager load everything or loop endlessly, we're going to use a nested set approach for our data. To make this easy, we pull in a great Laravel package called laravel-nestedset
.
We'll walk through installing the package with Composer, then use it to scaffold out our Category model along with its migration, factory, and seeder. In the migration, we set up our categories
table, including fields for title
, slug
(which needs to be unique), and the columns required for the nested set magic (like parent_id
, lft
, and rgt
). We run the migration and peek into the database to see those fields in action, noticing that the nested set package cleverly manages those extra columns for us.
After our database and model are set up, we'll quickly create a simple controller and route to begin displaying our categories. This includes setting up a new controller (CategoryIndexController
), adding the route, and creating a Blade view for the categories index page. We also update our navigation so we can jump to the categories page with ease.
This episode is mostly about setup, so we keep things basic for now. In the next one, we'll get into seeding some fake data, so we can actually see our nested categories system in action!