[5.8] Check for preserveKeys when serializing a collection from a resource#27985
[5.8] Check for preserveKeys when serializing a collection from a resource#27985taylorotwell merged 2 commits intolaravel:5.8from rodrigopedra:resources-keys
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? |
|
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
preserveKeysin 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::collectionreturns aAnonymousResourceCollectionand this class does not have apreserveKeysattribute, it fails on keeping the keys when serializing as currently we only check the$preserveKeysproperty in the object being serialized.This PR adds a method to the
ConditionallyLoadsAttributestrait 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