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 AppHttpResources;
use IlluminateHttpResourcesJsonJsonResource;
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 AppHttpControllers;
use AppModelsArticle;
use AppHttpResourcesArticleResource;
use IlluminateHttpRequest;
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.
The post Laravel whenLoaded – Performance Optimization via Conditional Relationship Loading appeared first on Laravel News.
Join the Laravel Newsletter to get all the latest
Laravel articles like this directly in your inbox.
Source: Read MoreÂ