Automatic model validation

Submitted by stidges - 11 years ago

It can sometimes be convenient to automatically validate your model when it gets created or updated. This is very easily achieved with Laravel through the use of Model events.

class Post extends Eloquent {
    
    /**
     * This is a useful switch to temporarily turn of automatic model validation.
     *
     * @var boolean
     */
    public static $autoValidate = true;
    
    /**
     * The rules to use for the model validation.
     * Define your validation rules here.
     *
     * @var array
     */
    protected static $rules = array();

    protected static function boot()
    {
        // This is an important call, makes sure that the model gets booted
        // properly!
        parent::boot();
        
        // You can also replace this with static::creating or static::updating
        // if you want to call specific validation functions for each case.
        static::saving(function($model)
        {
            if($model::$autoValidate)
            {
                // If autovalidate is true, validate the model on create
                // and update.
                return $model->validate();
            }
        });
    }
    
    public function validate()
    {
        // ... Your validation goes here ...
    }
}