0
0
Laravelframework~8 mins

API resource classes in Laravel - Performance & Optimization

Choose your learning style9 modes available
Performance: API resource classes
MEDIUM IMPACT
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.
Transforming Eloquent models to JSON for API responses
Laravel
return new UserResource($user);
Only selected attributes are serialized, reducing payload size and serialization overhead.
📈 Performance GainSaves 50-150kb in response size, reduces server CPU time, improves LCP by 100ms+
Transforming Eloquent models to JSON for API responses
Laravel
return response()->json($user->toArray());
Returns all model attributes including unnecessary data, increasing payload size and serialization time.
📉 Performance CostAdds unnecessary kilobytes to response, increasing LCP by 100-200ms on slow networks
Performance Comparison
PatternPayload SizeServer CPUNetwork TransferVerdict
Raw Model to JSONLarge (all attributes)High (full serialization)High (large JSON)[X] Bad
API Resource ClassSmall (selected fields)Low (optimized serialization)Low (smaller JSON)[OK] Good
Rendering Pipeline
API resource classes affect the server-side serialization stage before the browser receives data. Smaller, optimized JSON reduces network transfer time and speeds up browser rendering of content.
Server Serialization
Network Transfer
Browser Parsing
⚠️ BottleneckServer Serialization and Network Transfer
Core Web Vital Affected
LCP
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.
Optimization Tips
1Use API resource classes to send only necessary data fields.
2Avoid returning raw models directly to reduce payload size.
3Paginate large collections and use resource collections for better performance.
Performance Quiz - 3 Questions
Test your performance knowledge
How do API resource classes improve page load speed?
ABy increasing the number of database queries
BBy reducing JSON payload size and serialization time on the server
CBy caching the entire API response on the client
DBy adding more data fields to the response
DevTools: Network
How to check: Open DevTools, go to Network tab, filter API requests, inspect response size and timing.
What to look for: Look for smaller response payload size and faster time to first byte indicating efficient resource usage.