Skip to content

Instantly share code, notes, and snippets.

@byrnedo
Last active May 20, 2017 15:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save byrnedo/5d07ac221d93d4af149086dda3a0dd97 to your computer and use it in GitHub Desktop.
Save byrnedo/5d07ac221d93d4af149086dda3a0dd97 to your computer and use it in GitHub Desktop.
Add Nullable If validator in laravel 5.4
<?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);
});
...
<?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;
}
}
@elm91
Copy link

elm91 commented May 20, 2017

Would you please explain how I can use it with required_if and required_without?

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