CUSTOM ROUTE IN LARAVEL

Azen Moktan
2 min readApr 15, 2021

In Laravel by default provide separate route file for web and api. normally when we are building any application in Laravel we put web route on “web.php and api route in “api.php under route folder. but there is a need for separate route file when your project is huge. its always better to divide your code on sperate file as possible to make file clean and readable. If you are familiar with JavaScript technology as React or Vuejs or Angular , i am sure you are already familiar with this dividing to sub component .

Basic route file structure in Laravel.

Here Scenario is you are working on big project and you want to clean up your code into smaller chunks, in this case separate route file. here you want to create sperate route file for two user customer and seller.

Inside route folder lets create two file.

  1. customer.php
  2. seller.php

here customer.php will contain route associate with customer and seller.php will contain route associate with seller.php

route/customer.php

<?phpRoute::get('/customer/index', function () {dd('This is customer route');});

now we have created a new route file for customer as customer.php but it still wont work when we call it on web url .because we need to register this route in “app/Providers/RouteServiceProvider.php”.

app/Providers/RouteServiceProvider.php

on route RouteServicePovider.php create new function as mapCustomerRoutes() , you can name as ur project requirements.

protected function mapCustomerRoutes(){Route::prefix('customer')->namespace($this->namespace)->group(base_path('routes/customer.php'));}

Note: plz note base path currently we have customer.php inside route folder so our path is “routes/customer.php” but u can also structure as route/customer/customer.php by putting file inside customer folder in that case your base path will be as follow

base_path('routes/customer/customer.php'

now call function you just created map function which is default present in laravel inside RouteServiceProvider.php. our function name is mapCustomerRoutes so add this on map function inside RouteServiceProvider.php

public function map(){$this->mapApiRoutes();$this->mapWebRoutes();$this->mapCustomerRoutes();}

now run your Laravel project using artisan command

php artisan:serve

now on your web browser access route you just created as

http://localhost:8000/customer/*

Note: we are using customer prefix in our function mapCustomerRoutes() you can also use any prefix or no prefix as your project requirement.

--

--

Azen Moktan
0 Followers

A highly resourceful, innovative, and competent Software Engineer with extensive experience in the design , coding and problem solving .