Bird
0
0

Consider this Laravel route definition:

medium📝 Debug Q14 of 15
Laravel - Routing
Consider this Laravel route definition:
Route::get('/post/{id?}/{comment?}', function ($id = 1, $comment = 'none') {
    return "$id - $comment";
});

What is the error in this code?
AFunction parameters must not have default values
BDefault values cannot be strings
COptional parameters must be at the end; $id cannot be optional before $comment
DRoute parameters cannot have question marks
Step-by-Step Solution
Solution:
  1. Step 1: Check order of optional parameters

    In Laravel, optional parameters must come after all required ones and be at the end in order.
  2. Step 2: Analyze parameter order

    Here, $id is optional before $comment which is also optional, but $id is first. This is allowed only if both are optional and route matches accordingly.
  3. Step 3: Identify route matching issue

    Laravel cannot distinguish which parameter is missing if earlier optional parameters are skipped but later ones are present.
  4. Final Answer:

    Optional parameters must be at the end; $id cannot be optional before $comment -> Option C
  5. Quick Check:

    Optional params order matters [OK]
Quick Trick: Put optional params only at the end [OK]
Common Mistakes:
  • Ignoring order of optional parameters
  • Thinking default values cannot be strings
  • Believing question marks are invalid in routes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Laravel Quizzes