Member-only story
Dynamic Routing with Route Parameters — Let’s Learn Adonis 5, Lesson 2.1
View all lessons in the Let’s Learn Adonis 5 series here.
Route parameters give us a way to add dynamic routes to our route definitions so that we don’t have to define a route for each identity that’s within our database.
For example, without route parameters, in order to have a route for posts with an id
of 1, 2, and 3, we'd need to manually define the same route for each individual id
. That quickly becomes a scalability issue, as you can see below.
Route.get('/posts/1', () => 'get post 1')
Route.get('/posts/2', () => 'get post 2')
Route.get('/posts/3', () => 'get post 3')Route.put('/posts/1', () => 'get post 1')
Route.put('/posts/2', () => 'get post 2')
Route.put('/posts/3', () => 'get post 3')Route.delete('/posts/1', () => 'get post 1')
Route.delete('/posts/2', () => 'get post 2')
Route.delete('/posts/3', () => 'get post 3')
With route parameters, we can make the id
portion of the URL dynamic so that we only need to define the route once.
Defining A Route Parameter
Route parameters in Adonis start with a colon (:
), followed by whatever you want to name that parameter. Typically you'd name the route parameter after what value it should hold.
Route.get('/posts/:id', () => 'get post with provided id')
Route.put('/posts/:id', () => 'update post with provided id')
Route.delete('/posts/:id', () => 'delete post with provided id')
Here, we’ve named our route parameter id
to signify that the route parameter is meant to be a post id
value. So regardless if we send a GET request for http://localhost:3333/posts/1
, http://localhost:3333/posts/2
, or http://localhost:3333/posts/3
our GET route definition will be used.
Of course, be mindful of this because our :id
route parameter will match anything that's passed into that position in the url. For example, http://localhost:3333/posts/not-an-id
.