Organize your Laravel routes for better and maintainable code
Out of the box Laravel 5.5 provides 4 routes files api.php
, channels.php
, console.php
and web.php
.
The web.php
route file is for our web interface, api.php
is for APIs, console.php
is for artisan command registration and channels.php
is for broadcasting purpose.
We all know these things, so far nothing new in that right!
💡 What is the point of this post all about actually:
If you are working on a small application and you don’t have too many routes defined for your app then web.php
is enough for you, but what if you have hundreds or more routes defined, for example routes for Admin level, for customers, for some other type of users (related to auth) and the common unprotected routes which are available for all type of visitors.
⚠️ Then keeping all the routes together to just a single route file will easily make your routes unmanageable.
✅ Here is a really nice & clean solution to this problem which I found recently & wanted to share with you all
Assume we have three types of routes –
- For admin level
- For user level [can signup, login, manage profile etc.]
- Public routes [home, blog, contact page etc.]
Now we create two directories inside routes —
modified routes directory in laravel 5.5
☝ ️ routes/web
_ — _here goes all our web interface related routes
✌ ️ routes/api
— here all API related routes
routes files moved
Now we put the default api.php
inside api 📁 and the web.php
to the web 📁 and let’s leave the other two i.e. console.php
& channels.php
to their default place i.e. the routes 📁.
✔️Create a new file as admin.php
inside web 📁 this file will contain all our admin related web routes then
✔️create user.php
too in there which will represent all the routes related to user level
🎯 Here is the tricky part:
open Providers/RouteServiceProvider.php
_ _ — this file is responsible for bootstrapping all routes of our application. Check the map()
method to understand how it recognizes different routes files
the map() method inside Providers/RouteServiceProvider.php
check the mapApiRoutes()
& mapWebRoutes()
methods, they are just targeting the web.php
and api.php
which we’ve already moved, so let’s change the same in there
change the base_path() of two methods accordingly
Now create new methods for both admin.php
& user.php
inside RouteServiceProvider.php
create new methods for both type of routes
see how we were able to set the prefix , controller namespace & middleware! you can customize them as per your app
now simply call them from the map()
method of RouteServiceProvider
update the map() method accordingly
⛳️ The final step:
now open routes/web/user.php
and add some test route
navigate to your-laravel.app/user/test
and its done 😱
you have successfully been able to separate different routes for your app, it looks so much clean and easy to maintain too isn’t?
_Thanks for reading! Have Fun, Happy Coding !!