In Laravel, you can create separate route files to organize your routes better. Here’s how you can do it:
Step 1: Create a New Route File
You can create additional route files inside the routes/ directory. For example:
-
Admin Routes → Create
routes/admin.php -
API Routes → Create
routes/custom_api.php -
User Routes → Create
routes/user.php
Step 2: Define Routes in the New Files
Example for routes/admin.php:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/dashboard', function () {
return 'Admin Dashboard';
});
Example for routes/user.php:
Step 3: Load Custom Route Files in RouteServiceProvider
-
Open
app/Providers/RouteServiceProvider.php -
Inside the
boot()method, include your new route files:
public function boot()
{
parent::boot();
$this->routes(function () {
Route::middleware('web')
->group(base_path('routes/user.php'));
Route::middleware('web')
->prefix('admin') // Routes under "/admin" prefix
->group(base_path('routes/admin.php'));
});
}
If you’re adding an API route, use:
Route::middleware('api')
->prefix('custom-api')
->group(base_path('routes/custom_api.php'));
Step 4: Clear Cache and Test
Run:
</p> <p data-start="1463" data-end="1467">php artisan route:clear php artisan serve</p> <p data-start="1463" data-end="1467">
Then visit:
-
http://127.0.0.1:8000/dashboard→ Admin route -
http://127.0.0.1:8000/profile→ User route
This method helps keep your routes organized and scalable.
