Consider this Laravel route definition:
Route::get('/user/{id?}', function ($id = null) { return $id ?? 'guest'; });What will be the output when you visit /user URL?
Route::get('/user/{id?}', function ($id = null) { return $id ?? 'guest'; });
Think about what happens when an optional parameter is not given in the URL.
Laravel allows optional route parameters by adding a question mark ?. If the parameter is missing, the default value in the function is used. Here, $id defaults to null, so the null coalescing operator ?? returns 'guest'.
Choose the correct Laravel route definition that sets an optional parameter page with a default value of 1.
Remember that optional parameters must have a question mark in the route and a default value in the function.
Option A correctly marks the route parameter as optional with {page?} and sets a default value $page = 1 in the closure. Option A is missing the question mark, so the parameter is required. Option A does not set a default value in the function signature. Option A sets default to null but does not provide the default 1.
Given this Laravel controller method:
public function show($category = 'all', $page = 1) {
return "Category: $category, Page: $page";
}If the route is defined as Route::get('/items/{category?}/{page?}', [ItemController::class, 'show']); and the URL /items/books is visited, what is the output?
public function show($category = 'all', $page = 1) { return "Category: $category, Page: $page"; }
Think about how Laravel matches optional parameters in order.
When visiting /items/books, Laravel assigns 'books' to the first optional parameter $category. Since $page is not provided, it uses the default value 1. So the output is 'Category: books, Page: 1'.
Consider this route:
Route::get('/profile/{user?}/{section?}', function ($user = 'guest', $section = 'overview') {
return "$user - $section";
});Visiting /profile returns a 404 error. Why?
Route::get('/profile/{user?}/{section?}', function ($user = 'guest', $section = 'overview') { return "$user - $section"; });
Think about how Laravel matches optional parameters in sequence.
Laravel requires that optional parameters be provided in order. If you have multiple optional parameters, you cannot skip the first and provide the second. Visiting /profile provides no parameters, so Laravel expects at least the first optional parameter to be present if the second is optional. This causes a 404.
Given these two routes:
Route::get('/product/{id}', function ($id) { return "Product $id"; });
Route::get('/product/{id?}', function ($id = 'default') { return "Optional Product $id"; });What happens when you visit /product and why?
Think about how Laravel matches routes in order and optional parameters.
Laravel matches routes in the order they are defined. The first route requires an id, so /product without id does not match it. The second route has an optional id, so /product matches it and returns 'Optional Product default'.