Skip to content

Instantly share code, notes, and snippets.

@shkm
Last active December 16, 2015 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shkm/5434003 to your computer and use it in GitHub Desktop.
Save shkm/5434003 to your computer and use it in GitHub Desktop.
Laravel self-validating model. Child models need only extend `getRules()` and return their own rules array. Loosely based on Jeffrey Way's (https://tutsplus.com/lesson/validating-with-models-and-event-listeners/).
<?php
abstract class ValidatingModel extends \Eloquent
{
public $errors;
public static function boot()
{
parent::boot();
static::saving(
function ($model) {
return $model->validate();
}
);
}
public function validate()
{
$validation = \Validator::make($this->attributes, $this->getRules());
if ($validation->passes()) {
return true;
}
$this->errors = $validation->messages();
return false;
}
abstract protected function getRules();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment