Last active
December 16, 2015 12:19
-
-
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/).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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