-
Notifications
You must be signed in to change notification settings - Fork 11k
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
Add whenKeyExists method to ConditionallyLoadsAttributes #32662
Comments
Could you explain why you would want a resource in your example? It doesn't seem to add anything except for a "map" that doesn't do anything and returning the select directly would make more sense. That being said, you can already conditionally merge attributes (please scroll to "Merging Conditional Attributes") |
@koenhoeijmakers the example I provided is just an example of the functionality I want, in my case I am returning a paginated resource and am also using other conditional methods in the resource. I am not sure what you meant by your second comment, can you please provide an example what you mean? |
|
This is the way it works. You're explicitly stating the fields that you should returned in the |
@koenhoeijmakers you mean like this? 😏 public function toArray($request)
{
return [
'id' => $this->id,
$this->mergeWhen(array_key_exists('name', $this->resource->toArray()), [
'name' => $this->name
]),
$this->mergeWhen(array_key_exists('email', $this->resource->toArray()), [
'email' => $this->email
]),
$this->mergeWhen(array_key_exists('email_verified_at', $this->resource->toArray()), [
'email_verified_at' => $this->email_verified_at
]),
$this->mergeWhen(array_key_exists('created_at', $this->resource->toArray()), [
'created_at' => $this->created_at
]),
];
} |
I don't see why this is different form |
Description:
Classes JsonResource and ResourceCollection won't check whether the resource has the specified fields. e.g. when query has the
select()
method or specified columns inget()
.Specifying fields is a JSON:API standard.
Steps To Reproduce:
After running http://example.test/users?fields=id,email,email_verified_at
Expected output:
Actual output:
The text was updated successfully, but these errors were encountered: