Skip to content

Instantly share code, notes, and snippets.

@wgmv
Forked from robert-moore96/ValidatesOnSave.php
Created June 1, 2018 18:59
Show Gist options
  • Save wgmv/7c9d49b92caf4a2bf04ae91696ce4e2a to your computer and use it in GitHub Desktop.
Save wgmv/7c9d49b92caf4a2bf04ae91696ce4e2a to your computer and use it in GitHub Desktop.
<?php
namespace App\Traits;
use Validator;
trait ValidatesOnSave
{
protected static function bootValidatesOnSave()
{
static::saving(function ($model) {
if (method_exists($model, 'setDefaultValues')) {
$model->setDefaultValues();
}
$model->validate();
});
}
public function validation()
{
throw new \Exception("Model must override 'validation()' method with intended rules");
}
public function validate()
{
Validator::make($this->attributes, $this->validation())->validate();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment