How To Create Custom Route File in Laravel 10 Tutorial

Reading Time: 7 minutes
801 Views

If you are building a large web application , then surely you have several routes and their modules. Do you think, if you write all routes into a single file i.e web.php then it will be manageable. No it’s not. It will be very tough to manage all routes from one place.

The routes file in Laravel 10 serves as the starting point for establishing the application’s endpoints and actions. While Laravel includes a default routes file, there may be times when you wish to create custom route files to better organise and manage your application’s routes.

Read More: How To Create Custom Artisan Command in Laravel 10

In this detailed article, we will walk you through the process of generating custom route files in Laravel 10. You can group routes based on functionality, modules, or any other logical grouping that suits the structure of your application by generating different route files. This method encourages code organisation and improves the maintainability of your routes.

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Route Prefix (A Basic Route Example)

Let’s say we have an application in which we have modules as Admin, Customer.

If we write all routes of these two given modules into default route file i.e web.php. So, it will look like this:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\CustomerController;

Route::get('/', function () {
    return view('welcome');
});

// Admin Routes
Route::prefix("admin")->group(function(){
   Route::get("create-user", [AdminController::class, "createUser"]);
   Route::get("list-users", [AdminController::class, "listUsers"]);
   Route::get("edit-user", [AdminController::class, "editUser"]);
});

// Customer Routes
Route::prefix("customer")->group(function(){
   Route::get("list-purchase", [CustomerController::class, "listPurchase"]); 
   Route::get("list-blogs", [CustomerController::class, "listBlogs"]);
   Route::get("create-blog", [CustomerController::class, "createBlog"]);
});

//...

For now, we have considered only two modules inside laravel application. But in case for 20 modules and their routes inside web.php file, it will be too much lengthy and messy as well.

Now question is, how to manage then?

Here, comes the concept of Custom Route File in laravel.

Read More: How To Generate Unique Slug in Laravel 10 Tutorial

Custom Route Files (Module wise Separation)

Custom route files are those files which helps you to manage the application routes module wise and provide the flexibility to manage application.

For example,

Again, we are assuming the same modules as above Admin and Customer.

Create files as admin.php and customer.php as per requirement into /routes folder.

Open admin.php file from /routes folder. Inside this file we will place all admin related routes.

<?php

use Illuminate\Support\Facades\Route;

// Admin Routes
Route::prefix("admin")->group(function(){
   Route::get("create-user", [AdminController::class, "createUser"]);
   Route::get("list-users", [AdminController::class, "listUsers"]);
   Route::get("edit-user", [AdminController::class, "editUser"]);
});

Open customer.php from /routes folder. Inside this file we will place all customer related routes.

<?php

use Illuminate\Support\Facades\Route;

// Customer Routes
Route::prefix("customer")->group(function(){
   Route::get("list-purchase", [CustomerController::class, "listPurchase"]); 
   Route::get("list-blogs", [CustomerController::class, "listBlogs"]);
   Route::get("create-blog", [CustomerController::class, "createBlog"]);
});

Now, You can see.

Successfully, we have separated each module routes into different different route files. Every route is too much readable according to module.

Read More: How To Get HTTP Hostname In Laravel 10 Tutorial

How To Register Custom Route Files?

We will register custom route file via RouteServiceProvider.

Open RouteServiceProvider.php file from /app/Providers folder. Next, you can add your custom route files here.

<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to the "home" route for your application.
     *
     * This is used by Laravel authentication to redirect users after login.
     *
     * @var string
     */
    public const HOME = '/home';

    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));

            // Admin Route file 
            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/admin.php'));

            // Customer Route file
            Route::middleware('web')
                ->namespace($this->namespace)
                ->group(base_path('routes/customer.php'));
        });
    }

    /**
     * Configure the rate limiters for the application.
     *
     * @return void
     */
    protected function configureRateLimiting()
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });
    }
}

Concept

Add routes linking to boot() method.

// Admin Route file 
Route::middleware('web')
    ->namespace($this->namespace)
    ->group(base_path('routes/admin.php'));

// Customer Route file
Route::middleware('web')
    ->namespace($this->namespace)
    ->group(base_path('routes/customer.php'));

Here, as we can see we are using the default middleware web to both route files admin.php and customer.php.

In case if you have some different middleware then you can pass and use it.

All we done !

Application Testing

Run this command into project terminal to start development server,

php artisan serve

Admin URLs:

URL: http://127.0.0.1:8000/admin/create-user and all.

Customer URLs:

URL: http://127.0.0.1:8000/customer/list-purchase and all.

We hope this article helped you to learn about How To Create Custom Route File in Laravel 10 Tutorial in a very detailed way.

Read More: How to Check If a File Exists in Laravel 10 Tutorial

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.