When building Laravel applications that serve as APIs, the amount of data transferred over the network is equally critical for performance. This lesson explores how to minimize API response size.
The Problem: Unnecessary Data Transfer
Even with server-side optimizations like query limits in place, APIs often return excessive data that clients don't actually need. This creates several issues:
- Increased bandwidth usage
- Slower response times for clients
- Higher data consumption for mobile users
- Unnecessary processing on client devices
Consider a simple API endpoint returning posts with their associated users:
// Unoptimized approachreturn Post::with('user') ->latest() ->take(100) ->get();
Testing this endpoint with an API client reveals:
- Response time: 43ms (relatively fast)
- Data transferred: 516KB

The issue? We're returning every column from both tables, including lengthy post content and user descriptions that the client doesn't need.
The Solution: Return Only What Is Needed
We can limit post only to...