Performance: API resource classes
API resource classes affect the server response time and the size of JSON payloads sent to the client, impacting page load speed and interaction responsiveness.
Jump into concepts and practice - no test required
return new UserResource($user);return response()->json($user->toArray());| Pattern | Payload Size | Server CPU | Network Transfer | Verdict |
|---|---|---|---|---|
| Raw Model to JSON | Large (all attributes) | High (full serialization) | High (large JSON) | [X] Bad |
| API Resource Class | Small (selected fields) | Low (optimized serialization) | Low (smaller JSON) | [OK] Good |
API Resource Class in Laravel?UserResource?new UserResource($user).UserResource::collection($user) is for multiple models, not a single one.id=5 and name='Alice'?
class UserResource extends JsonResource {
public function toArray($request) {
return [
'user_id' => $this->id,
'user_name' => $this->name
];
}
}
// In controller:
return new UserResource($user);class ProductResource extends JsonResource {
public function toArray($request) {
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price
];
}
}
// In controller:
return ProductResource::collection($products);is_admin to your UserResource that only appears if the user has admin rights. Which is the best way to do this in the toArray method?