Out of the box, Laravel provides 4 different route files to manage your application routes. For a simple web application, this might be sufficient for most use cases but as your app grows, the routes will become harder to manage. In this post, I’ll guide you on how I manage my routes in a fairly complex application without sacrificing maintainability.
The idea is to split your routes into multiple files then load them independently inside the
RouteServiceProvider class. If we check on the
map method of
RouteServiceProvider, Laravel by default already maps two different routes to two different files,
web.php. We can extend this idea by further breaking down the routes inside
web.php into smaller files.
What I did for the application I’m currently developing is splitting the files based on the components or modules. Here is how it currently looks like inside my
├── api.php ├── breadcrumbs.php ├── channels.php ├── console.php ├── dashboard/ │ ├── account.php │ ├── addon.php │ ├── campaign.php │ ├── coupon.php │ ├── default.php │ ├── donation.php │ ├── notification.php │ ├── page.php │ ├── unauthenticated.php │ └── user.php ├── frontend/ │ └── campaign.php └── web.php
Once we’ve put the routes into the related files, all we need to do now is to map the routes similar to what Laravel does with the
For example, to map routes related to donations, I do:
And you’re good to go!
Update: In Laravel 8, things got changed a little bit, now it’s loaded via the
boot method but the overall concept is still applicable.