helium / eloquent-validator
Plugin for self-validation in Eloquent models
Requires
- illuminate/database: ^5.8||^6.0
- illuminate/validation: ^5.8||^6.0
README
Laravel and Eloquent offer out-of the box a framework for
validating model requests. However, whenever a model or
request must be validated, the validator must be created
and called manually. Helium's Eloquent Validator plugin
is designed to shift the paradigm of validation to the
model layer itself, including a simple validate()
method
in the model class itself, as well as the default behavior
or self-validating on save()
.
Usage
Rules
Define your model's schema rules as a property of your model class:
class User extends Model {
use SelfValidates;
$rules = [
'username' => 'required',
'password' => 'required',
...
];
}
Alternatively, overwrite the included getRules()
function:
class User extends Model {
use SelfValidates;
protected function getRules() {
return [
'username' => 'required',
'password' => 'required',
...
];
}
}
Overwriting getRules()
also allows you to return
schema rules dynamically, based on some other criteria
which you define.
Validate on Save
Helium's Eloquent Validator is configured by default
to validate a model's schema on save()
, and to throw
a ValidationException
on failure. However, you can
disable this default behavior by setting $validatesOnSave
:
class User extends Model {
use SelfValidates;
protected $validatesOnSave = false;
}
You can still manually validate your model's schema using
validate()
:
$u = new User;
...
$u->validate();