Skip to content

Instantly share code, notes, and snippets.

@MauMaGau
Last active August 17, 2016 13:48
Show Gist options
  • Save MauMaGau/7927864 to your computer and use it in GitHub Desktop.
Save MauMaGau/7927864 to your computer and use it in GitHub Desktop.
Laravel BaseModel
<?php
class BaseModel extends Eloquent
{
protected $rules = [];
protected $messages = [];
protected $errors;
public function validate(array $rules = [])
{
if(empty($rules)){
$rules = $this->rules;
}
$rules = $this->process_rules($rules);
$validation = Validator::make($this->attributes, $rules, $this->messages);
if($validation->passes())
{
return true;
}
$this->errors = $validation->errors();
return false;
}
public function errors()
{
return $this->errors;
}
public function save(array $options = [])
{
if($this->validate())
{
parent::save($options);
return true;
}
return false;
}
public function create(array $options = [])
{
if($this->validate())
{
parent::create($options);
return true;
}
return false;
}
public function save_without_validation(array $options = [])
{
parent::save($options);
}
public function process_rules(array &$rules)
{
$id = $this->getKey();
array_walk($rules, function(&$item) use ($id)
{
// 'typecast' item to array
if(!is_array($item))
{
$item = array('item');
}
foreach($item as &$an_item)
{
// Replace placeholders
$an_item = stripos($an_item, '{{id}}') !== false ? str_ireplace('{{id}}', $id, $an_item) : $an_item;
}
});
return $rules;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment