Skip to content

Route parameters

Andrea Mecchia edited this page May 29, 2018 · 5 revisions

Index > HTTP routing > Route parameters

Using route parameters

Route parameters allows you to tag parts of the request route as parameters:

$router->get("user/{username}", function($request, $args) { /* ... */ });

Parameters are enclosed in brackets and are available in the $args array, which is passed to the router action after the request parameter:

..., function($request, $args) { return Response::json(["email" => User::find($args["username"])->email]); }

It is possible to define multiple parameters:

$router->get("user/{user_id}/post/{post_id}", function($request, $args) { /* Availables as $args["user_id"] and $args["post_id"] */ });

Note that integers and decimal values are automatically cast to int and float

If more than one parameter with the same name are defined, only the value of the last one is saved:

"/{param}/{param}/{param}" -> "/only/the/last" -> $args["param"] is "last"

Complex parameters (since v0.2.3)

Parameters can be terminated by a quantifier (regex-like). Available quantifiers are:

  • {[0-9]} exactly the number of times specified
  • {[0-9]-[0-9]} a number of times between the specified range
  • * any number of times
  • + at least once
  • ? at most once

For example this route "/file/{filename}*" can be matched by any of the following requests:

  • /file/user.js with $args["filename"] = "user.js"
  • /file/avatar/png/0.png with $args["filename"] = "avatar/png/0.png"
  • /file/ with $args["filename"] = ""

When using quantifiers it may be necessary to split the components of the parameters (e.g. ["avatar", "png", "0.png"]). This can be easily done with an explode("/", $args[<param>]) or appending [] after the parameter name:

$router->get("/file/{filename[])*");

Model & Database >

Clone this wiki locally