Support the ongoing development of Laravel.io →
Input Eloquent Validation

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?

Last updated 3 years ago.
0

If you like the idea then search for Ardent and/or Magniloquent packages. They take this idea much further.

Last updated 3 years ago.
0

Creating a single instance of a class is never a big deal.

Last updated 3 years ago.
0

you could make the rules property and the validation method static, and just call it directly that way.

Last updated 3 years ago.
0

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 :)

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

websanova websanova Joined 8 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.