Skip to content

Instantly share code, notes, and snippets.

@jesseobrien
Created February 28, 2014 21:22
Show Gist options
  • Select an option

  • Save jesseobrien/9280168 to your computer and use it in GitHub Desktop.

Select an option

Save jesseobrien/9280168 to your computer and use it in GitHub Desktop.
Validatable trait
<?php
use Validator;
trait Validatable {
/**
* Validator instance for this check
* @var Validator
*/
protected $validator = null;
/**
* Determine if it's needed to check validity on save
* @var bool
*/
protected $checkValid = true;
/**
* Check to see if this model's attributes are valid
* @return bool
*/
public function isValid()
{
$this->validator = Validator::make($this->attributes, $this->getRules());
return $this->validator->passes();
}
/**
* Determine if the model will be checked for validation
* @return bool
*/
public function getsValidated()
{
return $this->checkValid;
}
/**
* Bypass validation checking on save
* @return Eloquent\Model
*/
public function bypassValidation()
{
$this->checkValid = false;
return $this;
}
/**
* Return the validation rules for this model
* @return array
*/
public function getRules()
{
return $this->rules;
}
/**
* Set the rules on the validator
*/
public function setRules(array $rules = array())
{
$this->rules = $rules;
}
/**
* Return the validator instance
* @return Validator
*/
public function getValidator()
{
return $this->validator;
}
/**
* Override the save functionality
* @param array
* @return mixed
*/
public function save(array $options = array())
{
if ($this->checkValid and ! $this->isValid())
{
throw new ValidationException($this->validator);
}
return parent::save();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment