theriddleofenigma / laravel-model-validation

Laravel model validation validates the data on model events. *Only for laravel applications.
https://theriddleofenigma.github.io/laravel-model-validation/
MIT License
32 stars 5 forks source link

Validator is not validating the correct data #9

Closed ctadlock closed 10 months ago

ctadlock commented 11 months ago

This code is calling model's toArray() to get the data to validate, but that data does not include hidden attributes. The concept of hidden is to hide attributes from public view; they should be included in the data set for validation. You cant use model's getAttributes() either as that transforms the data to be prepped for the database which changes its form. For example attributes that are set and casted as an array are represented as a string, which will fail if the array validation rule is applied. You cant use model's attributesToArray() as that does not include the default values set in protected $attributes = [..].

https://github.com/theriddleofenigma/laravel-model-validation/blob/d5d6703c96718be23a3deab0c3e37a96b5fde77d/src/ModelValidator.php#L73

I have a similar internal validation framework to this project. When I ran into this bug I found that every other example and project like this has the same bug. How I solved it was with merging these two arrays. getAttributes() has the defaults and attributesToArray() has the data in the proper casted format.

public function validationData(): array {
    return array_merge($this->getAttributes(), $this->attributesToArray());
}

public function validate(): void
{
    Validator::make($this->validationData(), $this->getRules())->validate();
}

If there is a better solution Id like to know.

ctadlock commented 10 months ago

After digging further into the Laravel code I settled on this for the validation data as its a modified version of public function attributesToArray()

public function validationData(): array {
    return $this->addCastAttributesToArray($this->getAttributes(), []);
}
theriddleofenigma commented 10 months ago

@ctadlock Thanks for pointing out. πŸ™πŸΌ I will add the helper method, validationData() {...} in ValidatorTrait.php. So that people can customize the data in the model itself based on the need. You can expect a new release in next few days with this change.

theriddleofenigma commented 10 months ago

@ctadlock I have made a new release v1.4.0. Please update the package to latest version to get the validationData(...) method helper. πŸŽ‰

Thanks for raising this issue. πŸ™πŸΌ