Last active
May 20, 2017 15:55
-
-
Save byrnedo/5d07ac221d93d4af149086dda3a0dd97 to your computer and use it in GitHub Desktop.
Add Nullable If validator in laravel 5.4
This file contains hidden or 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 | |
... | |
class AppServiceProvider extends ServiceProvider | |
{ | |
/** | |
* Bootstrap any application services. | |
* | |
* @return void | |
*/ | |
public function boot() | |
{ | |
$this->app['validator']->resolver(function($translator, $data, $rules, $messages) | |
{ | |
return new CustomValidator($translator, $data, $rules, $messages); | |
}); | |
... |
This file contains hidden or 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 | |
... | |
use Illuminate\Support\Arr; | |
use Illuminate\Validation\Validator; | |
class CustomValidator extends Validator | |
{ | |
/** | |
* Validate that an attribute exists when another attribute has a given value. | |
* | |
* @param string $attribute | |
* @param mixed $value | |
* @param mixed $parameters | |
* @return bool | |
*/ | |
protected function validateNullableIf($attribute, $value, $parameters) | |
{ | |
$this->requireParameterCount(2, $parameters, 'nullable_if'); | |
$data = Arr::get($this->data, $parameters[0]); | |
$values = array_slice($parameters, 1); | |
if (is_bool($data)) { | |
array_walk($values, function (&$value) { | |
if ($value === 'true') { | |
$value = true; | |
} elseif ($value === 'false') { | |
$value = false; | |
} | |
}); | |
} | |
if (in_array($data, $values)) { | |
// hit | |
$this->rules[$attribute][] = 'nullable'; | |
return true; | |
} | |
//miss | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Would you please explain how I can use it with required_if and required_without?