Recall & Review
beginner
What is an optional parameter in Laravel routes?
An optional parameter in Laravel routes is a route segment that may or may not be present in the URL. It allows the route to match URLs with or without that segment.
Click to reveal answer
beginner
How do you define an optional parameter in a Laravel route?
You define an optional parameter by adding a question mark (?) after the parameter name in the route URI, like {id?}.
Click to reveal answer
beginner
What should you do in the controller method to handle an optional parameter?
You should give the corresponding method parameter a default value, usually null, so the method works whether the parameter is passed or not.
Click to reveal answer
intermediate
Example: Define a route with an optional 'page' parameter and a controller method to handle it.
Route::get('/posts/{page?}', [PostController::class, 'index']);
public function index($page = 1) {
// Use $page or default to 1
}Click to reveal answer
intermediate
Why should optional parameters be placed at the end of the route URI?
Because Laravel matches routes from left to right, optional parameters must be last to avoid conflicts and ensure correct matching.
Click to reveal answer
How do you mark a route parameter as optional in Laravel?
✗ Incorrect
In Laravel, optional parameters are marked by adding a question mark after the parameter name inside curly braces.
What default value should you give a controller method parameter for an optional route parameter?
✗ Incorrect
You should give the controller method parameter a default value like null or another sensible default to handle when the parameter is missing.
Where should optional parameters be placed in a Laravel route URI?
✗ Incorrect
Optional parameters must be placed at the end of the URI to avoid routing conflicts and ensure proper matching.
What happens if you forget to give a default value to an optional parameter in the controller?
✗ Incorrect
If the controller method parameter has no default value and the optional route parameter is missing, Laravel throws an error.
Which of these is a valid route with an optional parameter in Laravel?
✗ Incorrect
The correct syntax for optional parameters is {parameterName?}, so {id?} is valid.
Explain how to create a Laravel route with an optional parameter and how to handle it in the controller.
Think about the question mark in the route and default values in the method.
You got /3 concepts.
Why is it important to place optional parameters at the end of a Laravel route URI?
Consider how Laravel reads the URL segments.
You got /3 concepts.