Laravel whenLoaded - Performance Optimization via Conditional Relationship Loading
Last updated on by Harris Raftopoulos
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.