[Proposal] Validate method on Models
It would be nice if models could be able to validate themselves by calling $model->validate(); if and only if the attribute $validation is not an empty value.
Something like this:
...
protected $validation = array();
...
public function validate()
{
if (empty($this->validation)) return true;
$validator = Validator::make($this->attributes, $this->validation);
return $validator->passes();
}
That way, if you define $validation in your model as array('bar' => 'required') you could simply:
$foo = new Foo;
$foor->bar = null;
$foo->validate(); // should return false
There could also be a getValidationErrors that returns the Validator's MessageBag.
Validation can be handled numerous ways. You can easily add this kind of functionality yourself if you want it this way. There is no reason this should be in the core model. On Aug 15, 2014 10:18 PM, "Benjamin Worwa" [email protected] wrote:
It would be nice if models could be able to validate themselves by calling $model->validate(); if and only if the attribute $validation is not an empty value.
Something like this:
...protected $validation = array();...public function validate(){ if (empty($this->validation)) return true;
$validator = Validator::make($this->attributes, $this->validation); return $validator->passes();}That way, if you define $validation in your model as array('bar' => 'required') you could simply:
$foo = new Foo;$foor->bar = null;$foo->validate(); // should return false
There could also be a getValidationErrors that returns the Validator's MessageBag.
— Reply to this email directly or view it on GitHub https://github.com/laravel/framework/issues/5474.
As @Garbee said, different people handle this in different ways.
See Ardent if you need this specific implementation.
Oh, and another reason this shouldn't be in core... Then the illuminate/database package becomes dependent upon the validator which makes a mess.
Shameless self promotion, but I was just browsing through issues. Check out dwightwatson/validating if you'd like a trait version of Ardent.
If we build a trait here, that wouldn't couple the default model, it would just make integration of the different framework components easier.
I believe Taylor has said before that he'd possibly accept a PR for something like this.
Laravel 5 now has form requests.