In this episode, we dive deep into advanced routing in Laravel, focusing on how to construct and resolve category URLs that contain all category slugs in their path, such as /shoes/boots/sale
instead of a simple /sale
.
We start by exploring the need to always show the full category hierarchy in the URL for improved clarity, navigation, and SEO. The episode shows step-by-step how to modify Laravel's route definitions to accept multiple wildcards and how to use a regex-based where
clause to match multi-segment category slugs.
On the controller side, we grab the path, split it into parts, and use the last segment to locate the correct category in the database. To ensure the URL is valid and the category really sits within the stated parent categories, we check that the trail of ancestors matches what’s in the path. This prevents users from tampering with URLs to get to categories through the wrong parentage.
Next, we update our Eloquent model to build category URLs dynamically in templates. To avoid performance issues (N+1 queries) as you go deeper into category trees, we cache the generated paths and explain how to bust that cache when categories are added or changed.
As a final polish, all the logic is refactored into custom route model binding using Laravel’s Service Provider, cleaning up controllers and making everything more maintainable.
Throughout the episode, you’ll see practical PHP and Laravel examples, anti-patterns to avoid, and thoughtful touches to ensure your app is robust, efficient, and user-friendly. By the end, you'll have a professional way to handle nested category URLs using multiple wildcards, custom model binding, and caching strategies.