Certainly! The `whenLoaded()` method is commonly used in ORM frameworks like Laravel's Eloquent to conditionally load relationships only if they are already loaded, which helps optimize queries by preventing unnecessary database calls.
What is `whenLoaded()`?
`whenLoaded()` is a method that allows you to check if a relationship is already loaded on a model instance and then perform some action only if it is. This is useful for optimizing queries and avoiding the N+1 query problem by ensuring you donât trigger additional lazy loading queries unintentionally.
How Does `whenLoaded()` Optimize Queries?
- Prevents unnecessary queries: It only executes code if the relationship data is already loaded.
- Avoids lazy loading: Prevents triggering additional queries when you access a relationship that isnât loaded.
- Improves performance: By controlling when related data is accessed or transformed, it keeps the number of queries minimal.
Example Scenario
Suppose you have two models: `Post` and `Comments`. A `Post` has many `Comments`. You want to display the post along with the number of comments, but only if the comments are already loaded (e.g., eager loaded earlier).
Code Snippet Using `whenLoaded()`
php
// Assume $post is an instance of the Post model
// Eager load comments to avoid N+1 queries
$post = Post::with('comments')->find(1);
// Use whenLoaded to safely access comments count only if loaded
$commentsCount = $post->whenLoaded('comments', function ($post) {
return $post->comments->count();
}, 0); // default to 0 if comments not loaded
echo "Number of comments: " . $commentsCount;
Explanation
1. Eager load `comments`: Using `with('comments')` ensures comments are loaded in one query.
2. Use `whenLoaded('comments', ...)`: This checks if the `comments` relationship is loaded.
3. Callback function: If loaded, it counts the comments.
4. Default value: If not loaded, it returns `0` to avoid triggering a lazy load.
Additional Example: Conditional Transformation
You can also use `whenLoaded()` to conditionally transform or append data only if the relationship is loaded.
php
$post = Post::with('comments')->find(1);
$commentsSummary = $post->whenLoaded('comments', function ($post) {
return $post->comments->map(function ($comment) {
return strtoupper($comment->content);
});
}, collect()); // return empty collection if not loaded
foreach ($commentsSummary as $commentContent) {
echo $commentContent . PHP_EOL;
}
Summary
- Use `whenLoaded()` to safely work with relationships only if they are preloaded.
- It helps avoid extra queries and improves performance.
- Itâs especially useful in APIs or views where you want to conditionally include related data.
If you want, I can provide examples for other ORMs or frameworks too!