Bird
Raised Fist0
Laravelframework~20 mins

API resource controllers in Laravel - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
API Resource Controller Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Laravel API resource controller method?
Consider a Laravel API resource controller with this method:
public function show($id) {
    return response()->json(['id' => $id, 'name' => 'Item '.$id]);
}

What JSON response will be returned when calling show(5)?
Laravel
public function show($id) {
    return response()->json(['id' => $id, 'name' => 'Item '.$id]);
}
A{"id":5,"name":"Item"}
B{"id":5,"name":"Item 6"}
C{"id":5,"name":"Item 5"}
D}"5 metI":"eman",5:"di"{
Attempts:
2 left
💡 Hint
Look at how the string concatenation works with the $id variable.
📝 Syntax
intermediate
2:00remaining
Which option correctly defines a Laravel API resource controller route?
You want to register a resource controller named ProductController for API routes in routes/api.php. Which route definition is correct?
ARoute::resource('products', 'ProductController');
BRoute::apiResource('products', ProductController);
CRoute::resource('products', ProductController::class);
DRoute::apiResource('products', ProductController::class);
Attempts:
2 left
💡 Hint
API resource routes exclude create/edit routes and require the controller class reference.
❓ state_output
advanced
2:00remaining
What is the HTTP status code returned by this API resource controller method?
Given this method in a Laravel API resource controller:
public function store(Request $request) {
    $data = $request->validate(['name' => 'required']);
    $item = Item::create($data);
    return response()->json($item, 201);
}

What HTTP status code will the client receive after a successful POST request?
Laravel
public function store(Request $request) {
    $data = $request->validate(['name' => 'required']);
    $item = Item::create($data);
    return response()->json($item, 201);
}
A201
B400
C500
D200
Attempts:
2 left
💡 Hint
201 means resource created successfully.
🔧 Debug
advanced
2:00remaining
Why does this Laravel API resource controller method cause a runtime error?
Examine this method:
public function update(Request $request, $id) {
    $item = Item::findOrFail($id);
    $item->update($request->all);
    return response()->json($item);
}

What causes the error when calling this method?
Laravel
public function update(Request $request, $id) {
    $item = Item::findOrFail($id);
    $item->update($request->all);
    return response()->json($item);
}
AUsing $request->all without parentheses causes a runtime error.
BfindOrFail does not exist on the Item model.
Cupdate method requires a second argument for validation.
Dresponse()->json cannot return model instances.
Attempts:
2 left
💡 Hint
Check how methods are called on the Request object.
🧠 Conceptual
expert
2:00remaining
Which statement best describes the difference between Route::resource and Route::apiResource in Laravel?
Choose the most accurate explanation about these two routing methods:
ARoute::apiResource creates routes only for GET requests, Route::resource creates routes for all HTTP verbs.
BRoute::resource creates all RESTful routes including web views, while Route::apiResource excludes routes for create and edit views.
CRoute::resource is deprecated and replaced by Route::apiResource in Laravel 9+.
DRoute::apiResource automatically applies authentication middleware, Route::resource does not.
Attempts:
2 left
💡 Hint
Think about which routes are included or excluded for API-only controllers.

Practice

(1/5)
1. What is the main purpose of an API resource controller in Laravel?
easy
A. To manage database migrations automatically
B. To handle user authentication and sessions
C. To generate HTML views for web pages
D. To provide standard methods for RESTful API actions like index, show, store, update, and destroy

Solution

  1. Step 1: Understand the role of API resource controllers

    API resource controllers in Laravel provide a set of predefined methods that correspond to common RESTful API actions such as listing resources, showing a single resource, creating, updating, and deleting resources.
  2. Step 2: Compare with other options

    Options A, B, and D describe other Laravel features unrelated to API resource controllers. Authentication, migrations, and HTML views are handled differently.
  3. Final Answer:

    To provide standard methods for RESTful API actions like index, show, store, update, and destroy -> Option D
  4. Quick Check:

    API resource controller purpose = standard RESTful methods [OK]
Hint: API resource controllers map REST actions automatically [OK]
Common Mistakes:
  • Confusing API controllers with authentication controllers
  • Thinking API resource controllers generate views
  • Assuming they handle database migrations
2. Which of the following is the correct way to register an API resource controller route in Laravel?
easy
A. Route::getResource('posts', PostController::class);
B. Route::resource('posts', PostController::class);
C. Route::apiResource('posts', PostController::class);
D. Route::api('posts', PostController::class);

Solution

  1. Step 1: Identify the method for API resource routes

    Laravel provides the apiResource method to register routes for API resource controllers, which excludes routes for creating and editing views.
  2. Step 2: Check other options

    Route::resource('posts', PostController::class); registers a full resource controller including web routes for create/edit views, which is not typical for APIs. Options C and D are invalid Laravel route methods.
  3. Final Answer:

    Route::apiResource('posts', PostController::class); -> Option C
  4. Quick Check:

    API resource route method = apiResource [OK]
Hint: Use apiResource for API-only routes, not resource [OK]
Common Mistakes:
  • Using Route::resource instead of Route::apiResource for APIs
  • Using non-existent route methods like getResource
  • Confusing web and API route registration
3. Given this API resource controller method in Laravel:
public function show($id) {
    return response()->json(['id' => $id, 'name' => 'Item '.$id]);
}

What will be the JSON response when calling GET /api/items/5?
medium
A. {"id":"5", "name":"Item 5"}
B. {"error":"Not Found"}
C. {"id":null, "name":"Item 5"}
D. {"id":5, "name":"Item 5"}

Solution

  1. Step 1: Analyze the show method

    The method returns a JSON response with an array containing 'id' set to the passed $id parameter and 'name' as 'Item ' concatenated with $id.
  2. Step 2: Substitute the URL parameter

    Calling GET /api/items/5 passes '5' as $id (string), so the JSON will be {"id":"5", "name":"Item 5"}.
  3. Final Answer:

    {"id":"5", "name":"Item 5"} -> Option A
  4. Quick Check:

    show method returns JSON with id="5" [OK]
Hint: Check parameter passed matches JSON output exactly [OK]
Common Mistakes:
  • Assuming id is integer instead of string
  • Expecting an error response for valid id
  • Confusing JSON structure returned
4. You have this route registration:
Route::apiResource('products', ProductController::class);

But when you try to access GET /products/create, you get a 404 error. Why?
medium
A. Because the ProductController is missing the create method
B. Because apiResource does not create routes for create and edit methods
C. Because the route URL is incorrect and should be /product/create
D. Because GET requests are not allowed on apiResource routes

Solution

  1. Step 1: Understand apiResource route behavior

    The apiResource method registers only API routes and excludes routes for creating and editing resources, such as /create and /edit, which are typically used for web forms.
  2. Step 2: Analyze the 404 error cause

    Since /products/create route is not registered by apiResource, accessing it results in a 404 error. This is expected behavior.
  3. Final Answer:

    Because apiResource does not create routes for create and edit methods -> Option B
  4. Quick Check:

    apiResource excludes create/edit routes [OK]
Hint: apiResource skips create/edit routes, use resource for them [OK]
Common Mistakes:
  • Expecting create route with apiResource
  • Thinking route URL is wrong
  • Assuming GET requests are blocked
5. 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
A. Route::apiResource('items', ItemController::class)->only(['index', 'show']);
B. Route::resource('items', ItemController::class)->except(['store', 'update', 'destroy']);
C. Route::apiResource('items', ItemController::class)->except(['create', 'edit']);
D. Route::resource('items', ItemController::class)->only(['index', 'show', 'create']);

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]
Hint: 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
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard