Bird
0
0

How can you define a route with an optional parameter category that defaults to 'all' if not provided, and use it inside the route callback?

hard📝 Application Q15 of 15
Laravel - Routing
How can you define a route with an optional parameter category that defaults to 'all' if not provided, and use it inside the route callback?
ARoute::get('/items/{category?}', function ($category) { return 'Category: ' . $category; });
BRoute::get('/items/{category}', function () { return 'Category: all'; });
CRoute::get('/items', function ($category = 'all') { return 'Category: ' . $category; });
DRoute::get('/items/{category?}', function ($category = 'all') { return 'Category: ' . $category; });
Step-by-Step Solution
Solution:
  1. Step 1: Define optional parameter in route

    Use curly braces with a question mark {category?} to make the parameter optional.
  2. Step 2: Set default value in function

    Assign a default value 'all' to $category in the function signature to handle missing parameter.
  3. Final Answer:

    Route::get('/items/{category?}', function ($category = 'all') { return 'Category: ' . $category; }); -> Option D
  4. Quick Check:

    Optional parameter + default value = Route::get('/items/{category?}', function ($category = 'all') { return 'Category: ' . $category; }); [OK]
Quick Trick: Use {param?} and default value in function for optional params [OK]
Common Mistakes:
  • Not setting default value in function
  • Omitting ? in route parameter
  • Defining parameter but not using it

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Laravel Quizzes