Customize Your API Versioning Route File In Laravel

Cloud
Parenting 數位研發
2 min readFeb 4, 2020
photo by Jamie Street on Unsplash

In Laravel framework, the api route file is separated to a single file. It’s clear to write the api route.

If we want add the version to the api route, it would be like behind:

Umm, it seems good. But if we have to add the v3 api route to the route file, we will find out that the route file is too large to manage.

To solve the situation, we would separate the versioning api file to a single file. Now, let we take a look how the Laravel separate the route file between web and api.

App\Http\Kernel.php

App\Providers\RouteServiceProvider.php

In the light of above, we should declare api v1 & v2 middleware group in Kernel.php file first, then we add mapApiVersionOneRoutes and mapApiVersionTwoRoutes to define the versioning api routes. Finally, Using the both functions in map function.

App\Http\Kernel.php

App\Providers\RouteServiceProvider.php

Congratulations! We have the pretty clear versioning api routes file now!

routes/api/v1.php

routes/api/v2.php

--

--

Cloud
Parenting 數位研發

後端工程師,主要使用 PHP,熟悉於使用 Laravel 來開發網站。最近開始接觸網站前端框架,目前熱衷於透過 Laravel 與 Vue.js 來開發 SPA ( Single Page Application ) 網站。