cloudcreativity / laravel-json-api

JSON API (jsonapi.org) package for Laravel applications.
http://laravel-json-api.readthedocs.io/en/latest/
Apache License 2.0
780 stars 109 forks source link

Nullable not being respected with new validator #414

Closed GIANTCRAB closed 5 years ago

GIANTCRAB commented 5 years ago

Laravel JSON API version: "v1.3.0"

This is my Users validator

class Validators extends AbstractValidators
{

    /**
     * Get resource validation rules.
     *
     * @param mixed|null $record
     *      the record being updated, or null if creating a resource.
     * @return mixed
     */
    protected function rules($record = null): array
    {
        $required = $record ? 'sometimes|required' : 'required';
        $unique = $record ? 'unique:users,email,'.$record->id : 'unique:users';

        return [
            'name' => "$required|string|min:1|max:255",
            'title' => 'nullable|string|max:127',
            'email' => "$required|email|$unique|min:1|max:255",
            'birth-date' => 'nullable|date_format:"d/m/Y"|before:today',
        ];
    }

}

When I submit the following HTTP request in my tests:

array:1 [
  "data" => array:4 [
    "type" => "users"
    "id" => "7857b5f1-abd0-4655-8df8-8116a0c73dbb"
    "attributes" => array:1 [
      "email" => "zkris@example.com"
    ]
  ]
]

This is the response I received:

array:1 [
  "errors" => array:1 [
    0 => array:4 [
      "status" => "422"
      "title" => "Unprocessable Entity"
      "detail" => "The birth-date must be a date before today."
      "source" => array:1 [
        "pointer" => "/data/attributes/birth-date"
      ]
    ]
  ]
]

I expected the new validator to respect my nullable rule. I think nullable for title is respected but birth-date is not? My feature test passed previously with the old validator. Is there something wrong with my code or is it something else?

lindyhopchris commented 5 years ago

As per the JSON API spec, it merges the values submitted by the client with the current attributes, and then passes them into the validator. That's described in the new chapter in the docs about validating update requests.

So for the data you've submitted, as there's no birth-date attribute, it will be using the value of the birth-date as it is on the model.

GIANTCRAB commented 5 years ago

Thanks