Skip to content

Instantly share code, notes, and snippets.

@jessarcher
Created March 8, 2021 08:11
Show Gist options
  • Save jessarcher/4ab86cbbc3470dbaf4d245a2edb2a8d8 to your computer and use it in GitHub Desktop.
Save jessarcher/4ab86cbbc3470dbaf4d245a2edb2a8d8 to your computer and use it in GitHub Desktop.
Laravel prohibited_if validation rule
<?php
namespace App\Providers;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
class ValidationServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extendDependent('prohibited_if', function ($attribute, $value, $parameters, $validator) {
$validator->requireParameterCount(2, $parameters, 'prohibited_if');
[$values, $other] = $this->prepareValuesAndOther($parameters, $validator);
if (in_array($other, $values, true)) {
return !$validator->validateRequired($attribute, $value);
}
return true;
});
Validator::replacer('prohibited_if', function ($message, $attribute, $rule, $parameters) {
return "The {$attribute} field is prohibited when the {$parameters[0]} field is {$parameters[1]}.";
});
}
/** @see \Illuminate\Validation\Concerns\ValidatesAttributes::prepareValuesAndOther() */
protected function prepareValuesAndOther($parameters, $validator)
{
$other = Arr::get($validator->getData(), $parameters[0]);
$values = array_slice($parameters, 1);
if (is_bool($other)) {
$values = $this->convertValuesToBoolean($values);
} elseif (is_null($other)) {
$values = $this->convertValuesToNull($values);
}
return [$values, $other];
}
/** @see \Illuminate\Validation\Concerns\ValidatesAttributes::covertValuesToBoolean() */
protected function convertValuesToBoolean($values)
{
return array_map(function ($value) {
if ($value === 'true') {
return true;
} elseif ($value === 'false') {
return false;
}
return $value;
}, $values);
}
/** @see \Illuminate\Validation\Concerns\ValidatesAttributes::convertValuesToNull() */
protected function convertValuesToNull($values)
{
return array_map(function ($value) {
return Str::lower($value) === 'null' ? null : $value;
}, $values);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment