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

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;
        }
    }
Last updated 3 years ago.
0

Yes, also see github.com/dwightwatson/validating for a more extensive example :)

Last updated 3 years ago.
0

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.

Last updated 3 years ago.
0

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™.

Last updated 3 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

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.