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, api.php and 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 routes folder:

├── 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 web.php.

For example, to map routes related to donations, I do:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
// app/Providers/RouteServiceProvider.php
...

public function map()
{
    $this->mapApiRoutes();

    $this->mapWebRoutes();

    $this->mapDonationWebRoutes(); // new method
}

protected function mapDonationWebRoutes(): void
{
    Route::middleware(['web', 'auth', 'verified'])
        ->namespace($this->namespace)
        ->prefix('donations')
        ->name('donations.')
        ->group(base_path('routes/dashboard/donation.php'));
}

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.