Naming, Grouping, & Prefixing Routes — Let’s Learn Adonis 5, Lesson 2.3
View all lessons in the Let’s Learn Adonis 5 series here.
As we’re defining our route definitions there’s actually something we can do now to help us vastly cut down on the amount of time needed to refactor in the future anytime we need to change one of our route’s paths. We can do this by naming our routes.
Naming Routes
By naming our routes we can then dynamically generate a URL for that route throughout our application using its name instead of manually supplying the URL. When we do this, should we need to change a route’s path in any way in the future, all we’d need to do is update the route’s definition and all the dynamically generated URLs will auto-update. We won’t need to worry about finding and updating each reference to the route.
We can name a route by chaining an extra method off the route’s definition called as
. The as
method then accepts as the first argument the name we'd like to give the route.
Route.get('/posts', () => `get all posts`).as('posts.index')
Here I’ve named my /posts
route posts.index
. We'll get more into generating URLs in the next lesson, but to show you the…