Courses

Laravel 12 Eloquent: Expert Level

API Return: Kilobytes Optimization

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Select only needed columns to reduce response size
- Further reduce by limiting relation columns
- Smaller responses improve speed and reduce bandwidth

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

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 approach
return 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...

The full lesson is only for Premium Members.
Want to access all 38 video+text lessons of this course? (1 h 34 min)

You also get:

  • 77 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord