You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/1-essentials/01-routing.md
+79Lines changed: 79 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -49,6 +49,85 @@ final readonly class AircraftController
49
49
}
50
50
```
51
51
52
+
### Optional parameters
53
+
54
+
Sometimes you may want a route to match both with and without a parameter. For instance, you might want `/aircraft` to show all aircraft, and `/aircraft/123` to show a specific aircraft. This can be achieved by marking route parameters as optional.
55
+
56
+
To mark a parameter as optional, prefix it with a question mark `?` inside the curly braces. The corresponding method parameter must either be nullable or have a default value.
In this example, both `/aircraft` and `/aircraft/123` will match the same route. When the parameter is not provided, the method parameter receives `null`.
82
+
83
+
Alternatively, you may provide a default value instead of using a nullable type:
84
+
85
+
```php app/AircraftController.php
86
+
#[Get(uri: '/aircraft/{?type}')]
87
+
public function filter(string $type = 'all'): View
88
+
{
89
+
// When /aircraft is requested, $type will be 'all'
90
+
// When /aircraft/commercial is requested, $type will be 'commercial'
91
+
}
92
+
```
93
+
94
+
You may also combine required and optional parameters. Optional parameters should come after required ones:
95
+
96
+
```php app/FlightController.php
97
+
use Tempest\Router\Get;
98
+
use Tempest\View\View;
99
+
use function Tempest\view;
100
+
101
+
final readonly class FlightController
102
+
{
103
+
#[Get(uri: '/flights/{id}/{?segment}')]
104
+
public function show(string $id, ?string $segment): View
105
+
{
106
+
// Matches both /flights/AA123 and /flights/AA123/departure
107
+
}
108
+
}
109
+
```
110
+
111
+
Multiple optional parameters are also supported:
112
+
113
+
```php app/AircraftController.php
114
+
#[Get(uri: '/aircraft/{?manufacturer}/{?model}')]
115
+
public function search(?string $manufacturer, ?string $model): View
116
+
{
117
+
// Matches /aircraft, /aircraft/cessna, and /aircraft/cessna/172
118
+
}
119
+
```
120
+
121
+
Optional parameters work seamlessly with [regular expression constraints](#regular-expression-constraints). Simply add the regex pattern after the parameter name:
122
+
123
+
```php app/AircraftController.php
124
+
#[Get(uri: '/aircraft/{?id:\d+}')]
125
+
public function show(?int $id): View
126
+
{
127
+
// Matches /aircraft and /aircraft/123 (numeric only)
128
+
}
129
+
```
130
+
52
131
### Regular expression constraints
53
132
54
133
You may constrain the format of a route parameter by specifying a regular expression after its name.
0 commit comments