[7.x] Conditionally returning appended attributes in API resources #33422
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.
I recently needed to return an attribute in an API Resource only when it had been explicitly appended to the model.
I couldn't find a nice public method to determine whether something had been appended to a model, so this PR adds a very simple public
hasAppended()
method to theHasAttributes
trait so it can be easily checked on any model instance.Then to improve the ergonomics inside the API Resource, I added a
whenAppended()
method to theConditionallyLoadsAttributes
trait that I think has nice symmetry with the other conditional "when" methods likewhen()
andwhenLoaded()
.The usage is then something like this:
This is particularly useful when an accessor contains information that should only sometimes be returned, or where an accessor might make additional database requests that you only want to occur deliberately.
Similar to the
whenLoaded()
method, you can optionally include the value to return if different than the accessor, as well as a default value.If this is a welcome addition, please let me know and I will add tests. I can also PR the "Conditional Attributes" section of the API Resources docs if warranted.