Require Route Parameter To Start With @ To Match

You can use route matchers to specify requirements on the route parameter. In this snippet, we require our username param to start with the @ character for the route to match.

Route parameter matchers give you the ability to enforce requirements upon the parameter in order for a given route to match a request.

If you'd like to learn more about route parameters and their matchers, check out our lesson "Dynamic Routing with Route Parameters".

Username Snippet

In the below snippet, the route parameter matcher (defined by the where method) is restricting this profiles.show route to only match if the username param specifically begins with @.

/@adocasts matches route
/adocasts does not match

// start/routes.ts

Route.get('/:username', 'ProfilesController.show')
  .as('profiles.show')
  .where('username', /^@/)

Purpose

By forcing our username param to start with @, we're able to simplify our profiles.show route, while still making use of other /something routes within our application.

For example:

// will only match if username starts with @
// if username does NOT start with @, this route will be bypassed
Route.get('/:username', 'ProfilesController.show')
  .as('profiles.show')
  .where('username', /^@/)

// when the previous route is bypassed, it'll be used to match this route
Route.get('/:slug', 'PostsController.show').as('posts.show')

Join The Discussion! (0 Comments)

Please sign in or sign up for free to join in on the dicussion.