Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

tylernathanreed's avatar

Organizing Routes into Separate Files or Classes

At my new job, I have been blessed with an eight year old PHP application that has been migrated to Laravel. It started off without a framework, and was then moved to the Velocity framework (Which is essentially Laravel 2). It has since been moved to Laravel 3, 4, and now 5.1. This thing is old. This application does a lot, and has a ton of code (about 1.5 million lines, not including any vendor files). Surprisingly, it has been kept fairly well, with only a few references to old Velocity code, some Laravel 3 stuff, and quite a bit of Laravel 4 (The Laravel 5.1 upgrade happened a couple of weeks ago).

With all of that said, there's about 600 unique routes, and all of them are pretty well structured, and I don't foresee the ability to reduce this count; in fact, it's still growing. None of the routes have names, and pretty much everything uses Route::controller, as to keep the routes.php file down to a mere 900 lines. I'd like to upgrade everything to named routes, and start using Route::resource and other methods where possible, as I'm not a fan of Route::controller (And apparently it was deprecated in 5.2). Either way, this needs to be organized, as the problem is only getting worse with time.

I can think of a few approaches, like creating an ~/app/Http/Routes folder, and filling it up with files. There's about 40 models, several API routes, and a few additional routes not really tied to anything specific. I'd like to organize this the best way possible. Any ideas?

I'm not really looking for a "put X in Y" solution, as that's my job (and you probably don't have enough information), but rather a clean way of referencing/defining routes outside the main routes.php file.

Using include <filepath>; is an obvious solution, so I'd like something a bit cleaner. For example, most of the file references in Laravel don't have the .php extension, and use a . instead of a / (Like layouts.master instead of layouts/master.php). I also want to avoid doing something like this: include __DIR__/Routes/api.php, as I'd much rather just do something like Route::include('api'), or some other clean alternative.

tl;dr:

I have way too many routes. How should I clean them up? What tactics have you guys used in the past, or are currently using?

0 likes
13 replies
usama.ashraf's avatar

@tylernathanreed just add this to your app/Providers/RouteServiceProvider.php's mapWebRoutes method.

$router->group([
      'namespace' => 'App\Http\Controllers',  'middleware' => 'web',
      ], function ($router) {
            require app_path('Http/new_routes_file.php');
 });

This will load your new routes file when the application bootstraps. Of course you can place your new file any where. I'd suggest making subfolder(s) inside Http that group together routes making semantic sense.

1 like
jlrdw's avatar

I wouldn't worry about reducing them, but I would work on putting the most accessed at top and work your way down. Besides, does it really matter if there are 10 or 2000. I have never tryed an include only if needed type thing with routes, but seems as though there would be a way to have a bunch load only if one from group will be used in an upcoming call, but I would play with it some sounds interesting. You have got me wondering about this now.

tylernathanreed's avatar

@usama.ashraf It would be nice to not have the "pull-in" logic in the routes.php file, so I think that this is a step in the right direction.

So, because I'm likely going to have 80+ of these files, I'd love to have these pull in automatically. So what about requiring all files that are in ~/app/Http/Routes/? I'd like to have folders within folders, so I'll probably need something recursive.

@JeffreyWay 's Finder Component tutorial definitely comes to mind for this.

@jlrdw Keep in mind that the routes.php file is currently reduced to about 900 lines because of Route::controller, which I'm phasing out. Seeing as I plan on using Route::resource, along with other methods, and adding several comments (as the current file has literally 3 lines, and they aren't super helpful), the routes.php file will easily explode into 10,000+ lines, which simply isn't manageable.

tylernathanreed's avatar

@usama.ashraf Nice, but I think I have a better solution:

use Symfony\Component\Finder\Finder;

function require()
{
    $files = Finder::create()
                ->in(app_path('Http/Routes')
                ->name('*.php');

    foreach($files as $file)
        require $file->getRealPath();
}

I could then move routes.php into ~/app/Http/Routes, and just stick all other Route files in there. That just leaves all of the organization to me!

tylernathanreed's avatar
Level 14

@usama.ashraf

Yeah. This is what I ended up with:

<?php

namespace App\Providers;

use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Symfony\Component\Finder\Finder;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator's root namespace.
     *
         * @var string
     */
    protected $namespace = 'App\Http\Controllers';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @param  \Illuminate\Routing\Router  $router
     *
     * @return void
     */
    public function boot(Router $router)
    {
        parent::boot($router);
    }

    /**
     * Define the routes for the application.
     *
     * @param  \Illuminate\Routing\Router  $router
     *
     * @return void
     */
    public function map(Router $router)
    {
        $this->mapWebRoutes($router);
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @param  \Illuminate\Routing\Router  $router
     *
     * @return void
     */
    protected function mapWebRoutes(Router $router)
    {
        $router->group($this->getDefaultGroup(), function ($router) {
            $this->requireWebRoutes($router);
        });
    }

    /**
     * Returns the Default Group for Routes.
     *
     * @return array
     */
    protected function getDefaultGroup()
    {
        return [
            'namespace' => $this->namespace,
            'middleware' => 'web'
        ];
    }

    /**
     * Requires all of the Files for Web Routes.
     *
     * @param  \Illuminate\Routing\Router  $router
     *
     * @return void
     */
    protected function requireWebRoutes(Router $router)
    {
        $files = Finder::create()
                ->in(app_path('Http/Routes')
                ->name('*.php');

        $this->require($files);
    }

    /**
     * Requires the specified Files.
     *
     * @param  array  $files  The specified Files.
     *
     * @return void
     */
    protected function require($files)
    {
        foreach($files as $file)
            require $file->getRealPath();
    }
}

And now I can just put everything in ~/app/Http/Routes, and each file will essentially act like routes.php.

2 likes
tylernathanreed's avatar

@usama.ashraf Just thought of an issue with my solution.

I plan to have an ~/app/Http/Routes/Models directory, and I'd like to have a Models namespace on it, so that I can group my Controllers similarly.

I'd like to be able to specify a custom group for each folder. How could that be done?

usama.ashraf's avatar

@tylernathanreed I'd rather you put your Controllers directory in app/Http. That is the default. You can create your Models folder there too. I guess routes have to look independent from controllers and models and what you're suggesting might be pushing it too much in terms of seemingly coupling one part of the application with another.

tylernathanreed's avatar

@usama.ashraf I like to separate my controllers by ones that handle models, and ones that don't. This means that I like to put my Controllers in ~/app/Http/Controllers/Models/, and apply a Models namespace to the Route::group that defines the routes for those controllers.

@EmilMoe That's very intriguing. That could effectively merge the Controller and Routing layers. It seems nice, but I feel like that's not good practice for some reason.

@usama.ashraf That's also very intriguing. However, there's really only two main modules in this, and everything else is connected to one or both of these. I do find myself doing this for support classes, like when I need to implement SMS or something, but I haven't considered sticking MVC concepts in them. That would require a huge change in flow, and it could weeks to actually do, but I'll definitely consider it for this project.

akshoy1904's avatar

So, I went ahead and wrote a little something about it. It’s a casual guide on how to segregate routes in Laravel apps, aiming to keep everything neat and easy to navigate. I think it could be a cool trick to add to our coding toolkit, especially for those gnarly projects that seem to grow wilder by the day.

I’d love for you guys to check it out and tell me what you think.

Here’s the link to the article: https://ravr.medium.com/organize-your-laravel-routes-for-better-and-maintainable-code-4ad9b76aed0f

Please or to participate in this conversation.