Created
March 16, 2014 21:00
-
-
Save rtablada/9589842 to your computer and use it in GitHub Desktop.
Modification of @fideloper's Validator to allow Model based validations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This allows you to validate for different scenarios based on named rules so you can do something like this:
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()
.