Laravel Tutorials

Laravel whenLoaded - Performance Optimization via Conditional Relationship Loading

Published Updated
Laravel whenLoaded - Performance Optimization via Conditional Relationship Loading image

Laravel's API Resources feature whenLoaded() to conditionally include relationship data in API responses, optimizing performance by preventing unnecessary database queries.

Here is an example of using the whenLoaded() method:

<?php
 
namespace App\Http\Resources;
 
use Illuminate\Http\Resources\Json\JsonResource;
 
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'posts' => PostResource::collection($this->whenLoaded('posts'))
];
}
}

If the "posts" relationship has not been loaded, the posts key will be removed from the response leaving you with just "id" and "name".

Here is an example of how this might work in a real world scenario:

<?php
 
namespace App\Http\Controllers;
 
use App\Models\Article;
use App\Http\Resources\ArticleResource;
use Illuminate\Http\Request;
 
class ArticleController extends Controller
{
public function index(Request $request)
{
$query = Article::query();
 
if ($request->boolean('with_author')) {
$query->with('author');
}
 
if ($request->boolean('with_comments')) {
$query->with(['comments' => fn($query) => $query->latest()]);
}
 
return ArticleResource::collection($query->paginate());
}
}
 
class ArticleResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'content' => $this->content,
'author' => new UserResource($this->whenLoaded('author')),
'comments' => CommentResource::collection(
$this->whenLoaded('comments')
),
'latest_comment' => $this->whenLoaded('comments', function() {
return new CommentResource($this->comments->first());
})
];
}
}

This implementation demonstrates efficient relationship handling through:

  • Dynamic relationship loading based on request parameters
  • Conditional inclusion of nested resources
  • Optimized query loading for better performance

Using whenLoaded() helps create lean, efficient APIs that optimize database queries while maintaining the flexibility to include related data when needed.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article