Laravel 9 How to Create Custom Route File Tutorial

Share this Article
Reading Time: 6 minutes
344 Views

If we are building a large web application , then surely we have several routes and their modules. Do we think if we 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.

Inside this article, we will see Laravel 9 How To Create Custom Route file. These route files as per application modules.

This article is very interesting to learn. This will be step by step guide for the concept of Custom Route file in laravel tutorial.

Learn More –

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 Example

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

If we write all routes all these given two modules into sample 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.

Here comes the concept of custom route file in laravel.

Custom Route Files

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 needed modules 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,

Successfully, we can see that we have separated each module routes into different different route files. Every route is readable module wise.

Register Custom Route Files

We will register custom route file via RouteServiceProvider.

Open RouteServiceProvider.php file from /app/Providers folder. 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());
        });
    }
}

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

Open project to terminal and type the command to start development server

$ php artisan serve

Admin URLs:

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

Customer URLs:

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

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

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

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.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5