laravel-json-api / laravel

JSON:API for Laravel applications

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Show or ignore attributes in resource

cruzvale33 opened this issue · comments

1.- Is possible to ignore an attribute in the resource when the query is index and show it when the method is show?? I have an attribute that I don't want show in the list because is a media type attribute related to a morph relationship (spatie media library), so this increase the number of queries for this resource.

2.- So, in another point if a request is a path, why I can't pass only the value of the attribute that I want to update? In example, I have two attributes:

  'cancelAuto' => [
                'sometimes',
                'boolean',
            ],
   'amount' => [
                $this->model() ? 'sometimes' : 'required',
                'nullable',
                JsonApiRule::number(),
            ],

If I try to update only cancelAuto, I receive an error that amount must be numeric, and viceverse.

For (1) your best bet would be to have the related information on a related resource, so the client can decide whether it wants that information in the response via the include path. The whole purpose of the spec is to give the client control of what it wants and doesn't want in a response, so implementing in a way that gives the client that control is always best.

If you do want to leave it as an attribute but control whether it is hidden or not, use this:
https://laraveljsonapi.io/docs/3.0/schemas/attributes.html#hiding-fields

For (2) you need to read the docs on updating resources. TLDR; the spec says any fields that the client doesn't provide, the server must assume it is the current value as held by the server. So that's what we do when we run the update validation - we merge in current field values for any fields not provided. This is fully documented here:
https://laraveljsonapi.io/docs/3.0/requests/resources.html#updating-resources

FYI it doesn't make sense (as far as I remember) to combine required and nullable because I think (but could be wrong) that a null value will fail required.

I'm closing this issue as it's not an issue - it's questions. If you've got more questions, I'd suggest asking on the Slack workspace.