-
Notifications
You must be signed in to change notification settings - Fork 11.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[5.8] Check for preserveKeys when serializing a collection from a resource #27985
Conversation
Ping @staudenmeir . Please take a look if you have the time |
An issue I see: class UserResource extends JsonResource
{
public $preserveKeys = true;
}
class UserCollection extends ResourceCollection
{
public $collects = 'App\Http\Resources\UserResource';
}
return new UserCollection(User::all()->filter->active); Here, the keys are preserved when they shouldn't be. Wouldn't your other suggestion solve this?
|
What if we move this to |
@staudenmeir , thanks for the suggestion, it is much nicer, can you please review it? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks great!
Thanks! @taylorotwell While fixing it I felt that this should have been implemented using an Interface, as we do with the ShouldQueue jobs, etc. As we expect the preserveKeys property to be true if this feature is needed. If you think this is a good approach, I can send a PR to the 5.9 branch |
@rodrigopedra , |
@TBlindaruk ok thanks, when I have the time I will try to send a PR so we can discuss there. |
As commented by @staudenmeir, when setting the
preserveKeys
in a resource, but generating a collection from it, the keys are not preserved.Before this PR the example in the docs should not work:
As the
JsonResource::collection
returns aAnonymousResourceCollection
and this class does not have apreserveKeys
attribute, it fails on keeping the keys when serializing as currently we only check the$preserveKeys
property in the object being serialized.This PR adds a method to the
ConditionallyLoadsAttributes
trait to handle both the cases of serializing a Resoruce or a Collection of resources.I used reflection to accomplish this, maybe to 5.9 we could change to using an Interface, I think it would clearer.
Worth noticing that @staudenmeir found this bug while working on issue #27950