helium/eloquent-validator

This package is abandoned and no longer maintained. The author suggests using the helium/laravel-helpers package instead.

Plugin for self-validation in Eloquent models

2.0.1 2020-02-05 18:52 UTC

This package is auto-updated.

Last update: 2020-04-29 16:46:57 UTC


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();