Author

Making Validation Trait in Laravel

Image

by Samarth Sinha on 2017-07-16 17:21:36

In PHP we use Traits for code reusibility. If we have to make same functions in different classes we can simply make a trait and use it in different classes. In Laravel Validation is an important part which we have to make in models and we have to do validations in objects. So we can make a ValidationTrait.php file in app\Traits folder and write the following codes.

<?php

namespace App\Traits;

use Validator;
use Illuminate\Support\MessageBag;
trait ValidationTrait
{
   //=============== return errors after validation ===================
   private $errors;

    private $skip_validations = false;

    public function set_skip_validation($val){
        $this->skip_validations=$val;
    }

    public function get_skip_validation(){
        return $this->skip_validations;
    }
    
   public function errors()
   {
      return $this->errors;
   }

    public function addError($messages){
        $this->initialize_or_create_error_obj()->merge($messages);
    }

    private function initialize_or_create_error_obj(){
        if($this->errors==null){
           $this->errors = new MessageBag();
        }
        return $this->errors;
    }

   public function validateObject()
    {
        $v = Validator::make($this->toArray(), $this->getValidationRules());
        if ($v->fails())
        {
            // set errors and return false
            $this->addError($v->errors());
            return false;
        }

        // validation pass
        return true;
    }

    protected function getValidationRules(){
       return array();
    }
}

Now use the above Trait in models like this: use App\Traits\ValidationRules. We can use getValidationRules() in Models to overwrite this function and get specific Validation Rules for each model

If you want to view the errors we can use errors(). To add errors in Objects use addError(). For validating Objects use validateObject(). If you dont want to use validations for some cases then use set_skip_validation(true), and get_skip_validation() to check if we have to use validations or not.


About the Author

  • avatar
    Samarth Sinha

    My name Samarth Sinha. I work on developing Web Applications using PHP and MySQL and in different frameworks of PHP like Laravel, CakePHP, CodeIgnitor and Smarty. In databases I have worked in MySQL and Postgres. I started this blog to share my knowledge to those who wants to start developing Web Applications using PHP.