Performance: API resource controllers
This affects server response time and client rendering speed by organizing API endpoints efficiently.
<?php use App\Http\Controllers\UserController; Route::apiResource('users', UserController::class); class UserController extends Controller { public function index() { /* list users */ } public function store() { /* create user */ } public function show($id) { /* show user */ } public function update($id) { /* update user */ } public function destroy($id) { /* delete user */ } }
<?php // Separate methods scattered in different controllers class UserController { public function createUser() { /* code */ } public function updateUser() { /* code */ } public function deleteUser() { /* code */ } public function getUser() { /* code */ } } // Routes defined individually for each method
| Pattern | Server Processing | Network Payload | Client Rendering | Verdict |
|---|---|---|---|---|
| Scattered CRUD methods | High due to duplicated logic | Larger due to inconsistent responses | Normal | [X] Bad |
| API resource controller | Optimized with unified logic | Smaller and consistent JSON payloads | Normal | [OK] Good |
apiResource method to register routes for API resource controllers, which excludes routes for creating and editing views.public function show($id) {
return response()->json(['id' => $id, 'name' => 'Item '.$id]);
}GET /api/items/5?Route::apiResource('products', ProductController::class);GET /products/create, you get a 404 error. Why?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.index and show methods to list and view items. Which is the best way to register the routes?apiResource is preferred because it excludes create/edit routes automatically.only method restricts the registered routes to just the specified methods, here 'index' and 'show'.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.Pass the test and this pattern moves unknown