Bird
0
0

You want to create an API resource controller that only supports index and show methods to list and view items. Which is the best way to register the routes?

hard📝 Application Q15 of 15
Laravel - Controllers
You want to create an API resource controller that only supports index and show methods to list and view items. Which is the best way to register the routes?
ARoute::apiResource('items', ItemController::class)->only(['index', 'show']);
BRoute::resource('items', ItemController::class)->except(['store', 'update', 'destroy']);
CRoute::apiResource('items', ItemController::class)->except(['create', 'edit']);
DRoute::resource('items', ItemController::class)->only(['index', 'show', 'create']);
Step-by-Step Solution
Solution:
  1. Step 1: Identify the correct route registration method for APIs

    Since this is an API controller, apiResource is preferred because it excludes create/edit routes automatically.
  2. Step 2: Limit routes to only index and show

    The only method restricts the registered routes to just the specified methods, here 'index' and 'show'.
  3. Step 3: Evaluate other options

    Route::resource('items', ItemController::class)->except(['store', 'update', 'destroy']); uses resource which includes web routes unnecessarily. Route::apiResource('items', ItemController::class)->except(['create', 'edit']); excludes create/edit but does not limit to only index/show. Route::resource('items', ItemController::class)->only(['index', 'show', 'create']); includes 'create' which is not needed and uses resource.
  4. Final Answer:

    Route::apiResource('items', ItemController::class)->only(['index', 'show']); -> Option A
  5. Quick Check:

    Use apiResource with only(['index', 'show']) for limited API routes [OK]
Quick Trick: Use apiResource with only() to limit API routes [OK]
Common Mistakes:
  • Using resource instead of apiResource for APIs
  • Not limiting routes and exposing unwanted methods
  • Including create/edit routes in API

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Laravel Quizzes