[11.x] Add whenExistsLoaded
method to conditionally include relationship existence attribute
#52295
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Introduction
This PR introduces a new method,
whenExistsLoaded
, to theIlluminate\Http\Resources\ConditionallyLoadsAttributes
trait. This method allows developers to conditionally include a relation existence attribute in their API resources if it was eager loaded.Background
Laravel's
JsonResource
currently provides several methods to conditionally include data in API responses based on whether certain relationships or attributes have been loaded. These methods include:whenLoaded
: to include a relationship if it was eager loaded.whenCounted
: to include a relationship count if it was eager loaded.whenAggregated
: to include an aggregated value if it was eager loaded.However, there is currently no method for conditionally including a relation existence attribute that has been eager loaded. This feature addresses that gap, providing a consistent API for conditional inclusion of various types of data.
Usage
Here is an example of how this new method can be used: