How to organize routes in Laravel

Jagadesha NH
Nov 8, 2017 · 1 min read

Well, laravel has a dedicated folder to keep all your routes at once place. By default it has a api.php, channels.php, console.php and web.php.

Imagine your working on a bigger application with multiple modules and 100s of routes!

Well lets get to organizing

so by default you have a folder called routes and create a new directory inside routes and name it api and inside api folder create a new folder and call it v1

Now you can put multiple files inside v1, for now lets assume we have common routes which are accessible to every one and a user routes which are accessible by the authenticated users and we have admin routes which are accessible by admin (user with role admin).

For this scenario we can create 3 new difference files inside our routes/api/v1 folder called common.php, user.php and admin.php.

Now our main api.php should include all the routes inside folder v1 with a prefix v1, so our final api.php should look like

Route::namespace('Api')->group(function() {

Route::prefix('v1')->namespace('V1')->group(function() {
include_once 'api/v1/common.php';
include_once 'api/v1/user.php';
include_once 'api/v1/admin.php';
});

});

and each of your route files inside v1 can have their own namespace and prefix for example, our admin.php would look something like.

Route::prefix('admin')->namespace('Admin')

HI THERE! Welcome to my blog. I'm 'Jagadesha NH', passionate programmer, fun-loving web developer living in the 'Silicon Valley of India'.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade