Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Named routes and groups

If a post address is written in ten templates, changing it means editing all ten. A route name solves this: links are built by name, and the address lives in one place. Groups let you set a shared part of the address for several routes at once.

A route name

The as method sets the name:

// start/routes.ts
import router from '@adonisjs/core/services/router'
 
router.get('/posts/:id', async ({ params }) => `Post ${params.id}`).as('posts.show')

Names are usually written with a dot: first the section, then the action. node ace list:routes shows the name posts.show next to the address.

Edge templates have a route function. It takes the name and the parameters:

{{-- resources/views/pages/home.edge --}}
<a href="{{ route('posts.show', { id: 5 }) }}">Fifth post</a>

The page gets a link to /posts/5. If you change the address in start/routes.ts to /articles/:id, the link updates by itself.

An address by name in code

In TypeScript the router builds the address, and the response object redirects to a named route:

// start/routes.ts
router.get('/latest', async ({ response }) => {
  return response.redirect().toRoute('posts.show', { id: 1 })
})
 
router.get('/link', async () => {
  return router.makeUrl('posts.show', { id: 7 })
})

/latest redirects the browser to /posts/1, and /link shows the string /posts/7.

Groups

router.group combines routes. prefix sets a shared address prefix, and as a shared name prefix:

// start/routes.ts
router
  .group(() => {
    router.get('/posts', async () => 'Posts in the admin area').as('posts')
    router.get('/users', async () => 'Users').as('users')
  })
  .prefix('/admin')
  .as('admin')

You get /admin/posts named admin.posts and /admin/users named admin.users. Later you will attach middleware to groups, for example a login check: one line protects every route in the group.

Resource routes

For the typical set of post actions there is a short form:

// start/routes.ts
const PostsController = () => import('#controllers/posts_controller')
 
router.resource('posts', PostsController)

One line registers seven routes with ready-made names:

Method and addressController methodName
GET /postsindexposts.index
GET /posts/createcreateposts.create
POST /postsstoreposts.store
GET /posts/:idshowposts.show
GET /posts/:id/editeditposts.edit
PUT /posts/:idupdateposts.update
DELETE /posts/:iddestroyposts.destroy

Controllers are covered in the next lesson.

Common mistake

If you pass route() a name that does not exist, or forget a parameter, the page fails with an error saying the route was not found or the id parameter is missing. Check names against node ace list:routes and pass every address parameter as the second argument.

Thanks for reading!

Donate to the site — we work hard for you.