How to create custom route file in laravel

1336
How to create custom route file in laravel

In some cases, we need to create our own separate custom route file in laravel application. By default, there are two types of route files in laravel i.e. web and api for web and api respectively. During large enterprise application development, we may need to create new route files for breaking our complex route file into multiple. Also, we may need multiple route file to for versioning our API. Whatever may be the reason, we can create multiple route files in laravel.

For this demo purpose, we will create a separate file for backend routes. Follow the below guidelines to create custom route file in laravel.

Create new route file

To create custom route file, we first need to create a file inside routes directory. We will name it as backend.php.

Register new route

Now we need to register the newly created route in RouteServiceProvider. Open up RouteServiceProvider from the directory App/Providers and create a new method with map prefix and Routes suffix. Thus, our new methods looks like below:

protected function mapBackendRoutes()
{
    Route::middleware('web')
         ->namespace($this->namespace)
         ->group(base_path('routes/backend.php'));
}

After creating new method, we need to call this from the map function.

public function map()
{
    ....
    $this->mapBackendRoutes();
    ...
}

Thus, our final RouteServiceProvider looks like below:

mapApiRoutes();

        $this->mapWebRoutes();

        $this->mapBackendRoutes();
    }

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }

    protected function mapBackendRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/backend.php'));
    }
}

This is all. Easy, isn’t it? If you face any issues, don’t forget to drop a comment below.
If you like this article, you may also want to read Laravel 5.7 CRUD example from scratch.

Read More Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.