Skip to content

Instantly share code, notes, and snippets.

@resmo
Created January 14, 2013 12:31
Show Gist options
  • Save resmo/4529738 to your computer and use it in GitHub Desktop.
Save resmo/4529738 to your computer and use it in GitHub Desktop.
Laravel 3 base model. I usually use it to extend from it.
<?php
class Base extends Eloquent {
/**
* @var
*/
public static $timestamps = true;
/**
* @var
*/
public $rules = array();
/**
* @var Laravel\Validator
*/
private $validator = null;
/**
* Returns validation rules
*
* @return array
*/
protected function getRules() {
return $this->rules;
}
/**
* Merge validation rule arrays
*
* @return void
*/
protected function addRules($rules) {
array_merge($rules, $this->rules);
}
/**
* Returns instance of validator
*
* @return Laravel\Validator
*/
public function getValidator() {
if ($this->validator == null) {
$this->validator = Validator::make($this->attributes, $this->getRules());
}
return $this->validator;
}
/**
* Validates the model
*
* @return boolean
*/
public function valid()
{
return $this->getValidator()->valid();
}
/**
* Validates and saves the model
*
* @return void
* @throw InvalidModelException
*/
public function save()
{
if(! $this->valid()) {
throw new InvalidModelException(get_class($this).' is not valid.');
}
parent::save();
}
/**
* Return validation error messages
*
* @return array
*/
public function getErrorMessages()
{
return $this->getValidator()->errors->all();
}
/**
* Returns model as string
*
* @return string
*/
public function __toString()
{
return $this->id;
}
}
class InvalidModelException extends Exception {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment