dwightwatson / validating

Automatically validating Eloquent models for Laravel
MIT License
968 stars 76 forks source link

Cast attributes before validating #147

Closed Propaganistas closed 8 years ago

Propaganistas commented 8 years ago

Eloquent allows to cast attributes upon getting or setting them. This allows developers to simply pass serializable entities such as arrays and objects to Eloquent without ever needing to worry about the database format.

Since this package hooks into storing values in the database, it seems obvious to me that validation is performed on the value a developer expects to get and set.

An example to justify this:

class Model {
    use ValidatingTrait;

    public $casts = [ 'myAttribute' => 'array' ];
    public $rules = [ 'myAttribute' => 'array' ];
}

This attribute can be set using an array because of $casts:

$model->myAttribute = array('value_1', 'value_2');

However validation performed by this package will happen on the casted database value, namely the json_encode version of the array, which in essence is just a plain string:

'["value_1","value_2"]'

So although the developer notifies Eloquent that the attribute is an array, he needs to set a string rule for the validator to effectively pass. This seems contradictory to me, hence this PR that takes into account casting.

dwightwatson commented 8 years ago

Awesome - thanks for taking the time to put this together.

It looks like the tests have failed on PHP 5.4, if you're able to sort that out I'll be more than happy to merge this in and tag it in a new release. Otherwise, I'll have a play with the broken test tomorrow morning (it's late where I am) and try and get it green again.

Propaganistas commented 8 years ago

It seems PHP 5.4 fails with the following error:

Maximum function nesting level of '256'

I'm not quite sure how to tackle this for now..