dwightwatson / validating

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

Make validationAttributeNames protected #163

Closed chrisschaetzlein closed 8 years ago

chrisschaetzlein commented 8 years ago

setValidationAttributeNames sets the given array as a public property, that is exposed as model attribute to Eloquent. Saving the model makes Eloquent try to save the model with the "validationAttributeNames" attribute, which will fail. Instead, make it a protected property.

dwightwatson commented 8 years ago

What error are you seeing specifically when using this? Eloquent doesn't just pick public properties off the model to persist to the database, all the attributes are stored in an array on the $attributes property.

chrisschaetzlein commented 8 years ago

When trying to save the model, I get the following error: ErrorException: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array(/home/matoki/api/vendor/laravel/framework/src/Illuminate/Support/helpers.php, 686)

It seems that eloquent tries to save the validationAttributeNames model property to the database.

chrisschaetzlein commented 8 years ago

Without making the validationAttributeNames property protected, $model->getModelAttributes() shows the previously set validationAttributeNames along with all the other model attributes.

chrisschaetzlein commented 8 years ago

To clear this up, I have the following function inside a model that uses the ValidatingTrait:

/**
 * Set the models validation rules defined by a given form
 *
 * @param Form $form
 */
public function loadValidationRules(Form $form)
{
    $this->setRules($form->getElementsRules());
    $fields = Field::all();
    $validationAttributeNames = [];
    foreach ($fields as $field) {
        $validationAttributeNames[$field->slug] = $field->name;
    }
    $this->setValidationAttributeNames($validationAttributeNames);
}`

After calling this function, $this->getModelAttributes() returns all the model attributes, but including a validationAttributeNames property. Unless I set the $validationAttributeNames model property to protected.

dwightwatson commented 8 years ago

Ah, of course, I'm a dingbat. Laravel was making it an attribute dynamically, I see what you're talking about now.

Sorry that took so long. Thanks for taking the time to put this together. I'll merge and tag this now.

chrisschaetzlein commented 8 years ago

:-) Thanks!