API resource controllers help organize your code to handle common actions like listing, creating, updating, and deleting data in a clean way.
API resource controllers in Laravel
php artisan make:controller NameController --api // In routes/api.php Route::apiResource('names', NameController::class);
The --api flag creates a controller without methods for showing forms, since APIs usually don't need HTML forms.
The apiResource method sets up routes for index, store, show, update, and destroy actions automatically.
php artisan make:controller ProductController --api
Route::apiResource('products', ProductController::class);
<?php namespace AppHttpControllers; use AppModelsProduct; use IlluminateHttpRequest; class ProductController extends Controller { public function index() { return Product::all(); } public function store(Request $request) { return Product::create($request->all()); } public function show(Product $product) { return $product; } public function update(Request $request, Product $product) { $product->update($request->all()); return $product; } public function destroy(Product $product) { $product->delete(); return response()->noContent(); } }
This example shows a TaskController with all API resource methods. The routes/api.php file uses apiResource to create routes automatically for tasks.
<?php namespace AppHttpControllers; use AppModelsTask; use IlluminateHttpRequest; class TaskController extends Controller { public function index() { return Task::all(); } public function store(Request $request) { return Task::create($request->all()); } public function show(Task $task) { return $task; } public function update(Request $request, Task $task) { $task->update($request->all()); return $task; } public function destroy(Task $task) { $task->delete(); return response()->noContent(); } } // In routes/api.php use AppHttpControllers\TaskController; Route::apiResource('tasks', TaskController::class);
API resource controllers do not include methods for creating or editing forms because APIs usually work with JSON data.
Use route model binding (like Task $task) to automatically get the model instance from the URL.
Remember to add validation in the store and update methods to keep data safe.
API resource controllers organize common API actions in one place.
Use php artisan make:controller NameController --api to create one quickly.
Use Route::apiResource to set up routes automatically for your API.
Practice
Solution
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.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.Final Answer:
To provide standard methods for RESTful API actions like index, show, store, update, and destroy -> Option DQuick Check:
API resource controller purpose = standard RESTful methods [OK]
- Confusing API controllers with authentication controllers
- Thinking API resource controllers generate views
- Assuming they handle database migrations
Solution
Step 1: Identify the method for API resource routes
Laravel provides theapiResourcemethod to register routes for API resource controllers, which excludes routes for creating and editing views.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.Final Answer:
Route::apiResource('posts', PostController::class); -> Option CQuick Check:
API resource route method = apiResource [OK]
- Using Route::resource instead of Route::apiResource for APIs
- Using non-existent route methods like getResource
- Confusing web and API route registration
public function show($id) {
return response()->json(['id' => $id, 'name' => 'Item '.$id]);
}What will be the JSON response when calling
GET /api/items/5?Solution
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.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"}.Final Answer:
{"id":"5", "name":"Item 5"} -> Option AQuick Check:
show method returns JSON with id="5" [OK]
- Assuming id is integer instead of string
- Expecting an error response for valid id
- Confusing JSON structure returned
Route::apiResource('products', ProductController::class);But when you try to access
GET /products/create, you get a 404 error. Why?Solution
Step 1: Understand apiResource route behavior
TheapiResourcemethod registers only API routes and excludes routes for creating and editing resources, such as /create and /edit, which are typically used for web forms.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.Final Answer:
Because apiResource does not create routes for create and edit methods -> Option BQuick Check:
apiResource excludes create/edit routes [OK]
- Expecting create route with apiResource
- Thinking route URL is wrong
- Assuming GET requests are blocked
index and show methods to list and view items. Which is the best way to register the routes?Solution
Step 1: Identify the correct route registration method for APIs
Since this is an API controller,apiResourceis preferred because it excludes create/edit routes automatically.Step 2: Limit routes to only index and show
Theonlymethod restricts the registered routes to just the specified methods, here 'index' and 'show'.Step 3: Evaluate other options
Route::resource('items', ItemController::class)->except(['store', 'update', 'destroy']); usesresourcewhich 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 usesresource.Final Answer:
Route::apiResource('items', ItemController::class)->only(['index', 'show']); -> Option AQuick Check:
Use apiResource with only(['index', 'show']) for limited API routes [OK]
- Using resource instead of apiResource for APIs
- Not limiting routes and exposing unwanted methods
- Including create/edit routes in API
Ready to prove it?
Pass the test and this pattern moves unknown
