I wrote a blog post here which explains how you can take Dayle Ree's model validation code and turn it into a trait.
Traits are a great way of implementing this kind of feature, rather than extending the Eloquent model!
Check it out :)
<?php
trait ValidationTrait {
public $errors;
public function validate($data) {
$Reflection = new \ReflectionClass(__CLASS__);
$ReflectionClass = $Reflection->newInstance();
if(empty($ReflectionClass->rules)) return TRUE;
$v = Validator::make($data, $ReflectionClass->rules);
if($v->fails()) {
$this->errors = $v->failed();
return FALSE;
}
return TRUE;
}
public function validationErrors() {
return $this->errors;
}
}
Yes, also see github.com/dwightwatson/validating for a more extensive example :)
I dont like to use an attribute to store validation rules. What if you want different validation rules for creating and updating ? What if you want to append the id of the instance to an unique rule so the updating works ? I prefer a getRules method which returns an array of rules.
Anyway there is so many real case example not suited to model validation that i prefer to use validation classes.
In our case our needs are met by this. We build our own custom validators where needed and the "rules are the rules". It works for us™.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community