-
Notifications
You must be signed in to change notification settings - Fork 1
Route parameters
Index > HTTP routing > 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
intandfloat
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"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.jswith$args["filename"] = "user.js" -
/file/avatar/png/0.pngwith$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[])*");