Bird
0
0

You want to create a Laravel route that accepts a required category and an optional page number with default 1. Which of these route and controller method pairs is correct?

hard📝 Application Q15 of 15
Laravel - Routing
You want to create a Laravel route that accepts a required category and an optional page number with default 1. Which of these route and controller method pairs is correct?
ARoute::get('/items/{category}/{page?}', [ItemController::class, 'index']);<br>public function index($category, $page = 1) { return "$category - $page"; }
BRoute::get('/items/{category?}/{page}', [ItemController::class, 'index']);<br>public function index($category = 'all', $page) { return "$category - $page"; }
CRoute::get('/items/{category}/{page}', [ItemController::class, 'index']);<br>public function index($category, $page = 1) { return "$category - $page"; }
DRoute::get('/items/{category?}/{page?}', [ItemController::class, 'index']);<br>public function index($category = 'all', $page = 1) { return "$category - $page"; }
Step-by-Step Solution
Solution:
  1. Step 1: Identify required and optional parameters in route

    The required parameter category must come first without a question mark. The optional page comes after with a question mark.
  2. Step 2: Match controller method parameters

    The method must have $category first (required) and $page second with default 1.
  3. Step 3: Check each option

    Route::get('/items/{category}/{page?}', [ItemController::class, 'index']);
    public function index($category, $page = 1) { return "$category - $page"; } matches the correct route and method signature. Others either reverse order or make required params optional incorrectly.
  4. Final Answer:

    Option A with required category and optional page correctly defined -> Option A
  5. Quick Check:

    Required first, optional after with defaults [OK]
Quick Trick: Required params first, optional with default after [OK]
Common Mistakes:
  • Making required params optional in route
  • Placing optional params before required ones
  • Not giving default values in method

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Laravel Quizzes