Skip to content

[7.x] Conditionally returning appended attributes in API resources#33422

Merged
taylorotwell merged 8 commits into
laravel:7.xfrom
jessarcher:append-helpers
Jul 3, 2020
Merged

[7.x] Conditionally returning appended attributes in API resources#33422
taylorotwell merged 8 commits into
laravel:7.xfrom
jessarcher:append-helpers

Conversation

@jessarcher
Copy link
Copy Markdown
Member

@jessarcher jessarcher commented Jul 3, 2020

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 the HasAttributes 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 the ConditionallyLoadsAttributes trait that I think has nice symmetry with the other conditional "when" methods like when() and whenLoaded().

The usage is then something like this:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'name' => $this->name,
        'email' => $this->email,
        'is_subscribed' => $this->whenAppended('is_subscribed'),
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];
}
return new UserResource($user->append('is_subscribed'));

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.

@jessarcher jessarcher changed the title Conditionally returning appended attributes in API resources [7.x] Conditionally returning appended attributes in API resources Jul 3, 2020
@taylorotwell
Copy link
Copy Markdown
Member

Seems simple enough. 👍

@taylorotwell
Copy link
Copy Markdown
Member

Feel free to continue with anything else you wanted to add here.

@jessarcher
Copy link
Copy Markdown
Member Author

Thanks @taylorotwell. I've added a few tests so I think it's good to go :)

Comment thread tests/Database/DatabaseEloquentModelTest.php
@taylorotwell taylorotwell merged commit 9c29794 into laravel:7.x Jul 3, 2020
@jessarcher jessarcher deleted the append-helpers branch July 3, 2020 22:58
@francoism90
Copy link
Copy Markdown

Thanks! I can finally remove my trait. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants