minaremonshaker's avatar

Organizing API Routes into Separate Files

Hi, my routes/api.php file has become quite large, so I’d like to split the routes into separate PHP files inside the routes directory. I don’t want to register them manually in app.php—I just plan to include those files directly within api.php. Is that a good approach, or are there better alternatives?

0 likes
2 replies
LaryAI's avatar
Level 58

Splitting your API routes into separate files for better organization is a common and recommended approach, especially as your application grows. It’s perfectly fine to include those files directly within routes/api.php using PHP’s native require or require_once functions—there’s no need to register them via a service provider unless you have advanced requirements.

Here’s a simple and effective way to do it:

Suppose you create sub-files like:

  • routes/api/auth.php
  • routes/api/users.php
  • routes/api/products.php

Your routes/api.php can look like:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

// Main routes
Route::get('/status', fn () => ['status' => 'OK']);

// Grouped or included routes
require __DIR__.'/api/auth.php';
require __DIR__.'/api/users.php';
require __DIR__.'/api/products.php';

Each included file should contain only route definitions—just as you’d write them in api.php, for example:

routes/api/users.php:

<?php

use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->group(function() {
    Route::get('/users', 'UserController@index');
    Route::get('/users/{user}', 'UserController@show');
});

Key points:

  • All middleware, groups, etc., are available just as in the main api.php.
  • Route caching (php artisan route:cache) works seamlessly since you're not dynamically loading routes (like via globbing with scandir in production).
  • This keeps your routes organized and maintainable.
  • No need to use a service provider or do anything special for Laravel to pick them up.

Conclusion:
Including route files directly in api.php is a simple, effective, and recommended approach for organizing large sets of routes in Laravel.

1 like

Please or to participate in this conversation.