0
0
Laravelframework~5 mins

Optional parameters in Laravel - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AUse parentheses around the parameter, like ({id})
BAdd a star after the parameter name, like {id*}
CUse square brackets around the parameter, like [{id}]
DAdd a question mark after the parameter name, like {id?}
What default value should you give a controller method parameter for an optional route parameter?
Anull or a sensible default
BAn empty string ''
CNo default value needed
DZero (0)
Where should optional parameters be placed in a Laravel route URI?
AAnywhere in the URI
BIn the middle of the URI
CAt the end of the URI
DAt the beginning of the URI
What happens if you forget to give a default value to an optional parameter in the controller?
ALaravel throws an error if the parameter is missing
BLaravel automatically assigns null
CThe route will not match
DThe controller method is skipped
Which of these is a valid route with an optional parameter in Laravel?
ARoute::get('/user/{?id}', ...);
BRoute::get('/user/{id?}', ...);
CRoute::get('/user/{id*}', ...);
DRoute::get('/user/[id]', ...);
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.