Laravel model validation with traits

Our application is built around fourty different models, and counting. The biggest thing we deal with is making sure that all of the data is entered correctly. For instance, names must be alpha (with some special characters), we use a custom email validator that allows for "pre-defined" email types which is in the format of @REASON and other validation formats.

Whilst we do of course use client-side validation to force the user to enter the expected formats, sometimes we need to handle third-party API's which dwindle from their expected results.

We handle all of this model validation with a custom trait that our models use when they need this kind of inline-data-validation. Taking Dayle Rees model example idea further, we drop the model - there is no need to extend Eloquent and we end up with this:

<?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;
        }
    }

Using it is simple too, pretty much how Dayle shows:

<?php

    class Customer extends Eloquent {
        use ValidationTrait;

        public $rules = array(
            'title'        => 'required',
            'first_name'   => 'required',
            'last_name'    => 'required',
            'e_mail'       => 'required|email',
            'phone_number' => 'required',
        );

    }

    $Customer = new Customer();

    if($Customer->validate(Input::all()) {
        // Save the new model.
    }else{
        return $Customer->validationErrors()
    }

Easy!


comments powered by Disqus