framework icon indicating copy to clipboard operation
framework copied to clipboard

[Proposal] Validate method on Models

Open bworwa opened this issue 12 years ago • 6 comments

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.

bworwa avatar Aug 16 '14 02:08 bworwa

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.

Garbee avatar Aug 16 '14 07:08 Garbee

As @Garbee said, different people handle this in different ways.

See Ardent if you need this specific implementation.

ibrasho avatar Aug 16 '14 09:08 ibrasho

Oh, and another reason this shouldn't be in core... Then the illuminate/database package becomes dependent upon the validator which makes a mess.

Garbee avatar Aug 16 '14 09:08 Garbee

Shameless self promotion, but I was just browsing through issues. Check out dwightwatson/validating if you'd like a trait version of Ardent.

dwightwatson avatar Aug 17 '14 03:08 dwightwatson

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.

franzliedke avatar Aug 20 '14 12:08 franzliedke

Laravel 5 now has form requests.

GrahamCampbell avatar Dec 28 '14 15:12 GrahamCampbell