I just came across an example that put the validation inside of a model like so:
class User extends Eloquent {
protected $table = 'users';
private $rules = array(
'email' => 'required|email',
'username' => 'required|min:6'
);
public function validate($input) {
return Validator::make($input, $this->rules);
}
}
I like how the rules are stored in there and it could even be improved by creating some kind of BaseClass
for the models and put the validation function in there. However to use it this way we need to instantiate the User
object first.
$user = new User();
$input = array();
$input['email'] = 'racerx@example.com';
$input['username'] = 'Short';
$valid = $user->validate($input);
if ($valid->passes()) {
echo 'Everything is Valid!';
} else {
var_dump($valid->messages());
}
As you can see if the validation fails it would be a waste to create the User
object. Is this a big issue? I like the idea of having all the validation info in my models, keeps things cleaner is creating that User
object negligible enough for the cleaner design with the validation in the models?
If you like the idea then search for Ardent and/or Magniloquent packages. They take this idea much further.
Creating a single instance of a class is never a big deal.
you could make the rules property and the validation method static, and just call it directly that way.
I use this version: https://tutsplus.com/lesson/validation-services/
You are gonna repeat the code for every model you want to validate with your version :)
I know it's nice to store rules in model ... but dont repeat code if you can find a better way :)
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community