As the size of the application grows, so does the number of routes. After some time, the route management becomes a challenge in itself. To combat that challenge, here is a way to trick laravel to autoload application routes.
First we will create an auto-loader function in AppServiceProvider
private function autoloadRoutes(): void
{
foreach (File::allFiles(base_path(self::ROUTE_MODULE_DIR)) as $file) {
Route::middleware(['web'])->group(function () use ($file): void {
$this->loadRoutesFrom(base_path(self::ROUTE_MODULE_DIR) . $file->getFilename());
});
}
}
Here, ROUTE_MODULE_DIR
is a constant declaration in the class.
const ROUTE_MODULE_DIR = 'routes/modules/';
Once the function is available, we can add the function to the register
method of the AppServiceProvider
public function register(): void
{
$this->autoloadRoutes();
}
And that's it. Now, whenever you create a new file with routes in the routes/module
directory, it will be auto loaded in the application.