Skip to content

Instantly share code, notes, and snippets.

@rtablada
Created March 16, 2014 21:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rtablada/9589842 to your computer and use it in GitHub Desktop.
Save rtablada/9589842 to your computer and use it in GitHub Desktop.
Modification of @fideloper's Validator to allow Model based validations
<?php namespace Initr\Services;
use Illuminate\Validation\Factory as LaravelValidator;
abstract class Validator
{
protected $validator;
protected $data = array();
protected $errors = array();
protected $rules = array();
protected $messages = array();
public function __construct(LaravelValidator $validator)
{
$this->validator = $validator;
}
public function with(array $data)
{
$this->data = $data;
return $this;
}
public function validate($data, $rules)
{
$validator = $this->validator->make(
$data,
$rules,
$this->messages
);
if ($validator->fails()) {
$this->errors = $validator->messages();
return false;
}
return true;
}
public function passes()
{
return $this->validate(
$this->data,
$this->rules
);
}
public function errors()
{
return $this->errors;
}
public function __call($method, $parameters)
{
$matches = array();
if (preg_match('/validate(.*)/', $method, $matches)) {
$rulesName = camel_case($matches[1]) . 'Rules';
$rules = $this->{$rulesName};
return $this->validate($parameters[0], $rules);
}
}
}
@rtablada
Copy link
Author

This allows you to validate for different scenarios based on named rules so you can do something like this:

use Initr\Services\Validator as BaseValidator;

class UserValidator extends BaseValidator
{
    public $createRules = [
        'email' => 'email|unique:users',
    ];

    public $updateRules = [
        'email' => 'email',
    ];
}

Then in your controller, you can call $validator->updateCreate($input) which will return if the validator passes. When the validator is failing, you can get the errors with $validator->errors().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment