Skip to content

Instantly share code, notes, and snippets.

@martindilling
Last active August 29, 2015 14:08
Show Gist options
  • Save martindilling/0b2a8950c70b7b7b8870 to your computer and use it in GitHub Desktop.
Save martindilling/0b2a8950c70b7b7b8870 to your computer and use it in GitHub Desktop.
Extended laravel validator to support validating each item in an array. Used http://stackoverflow.com/a/26537606 for the most of this.
<?php namespace Validators\ExtendedValidator;
use Illuminate\Validation\Validator;
/**
* Extending Laravels validator to support some extra validation rules.
*
* http://stackoverflow.com/a/26537606
*
* @author Martin Dilling-Hansen <[email protected]>
* @date 2014-10-24
*/
class ExtendedValidator extends Validator
{
/**
* Validate that each item in the array validates with the given validator.
*
* @param string $attribute
* @param mixed $value
* @param array $parameters
*
* @return bool
*/
public function validateEach($attribute, $value, $parameters)
{
// Transform the each rule
// For example, `each:exists,users,name` becomes `exists:users,name`
$ruleName = array_shift($parameters);
$rule = $ruleName . (count($parameters) > 0 ? ':' . implode(',', $parameters) : '');
foreach ($value as $arrayKey => $arrayValue) {
$this->validate($attribute . '.' . $arrayKey, $rule);
}
// Always return true, since the errors occur for individual elements.
return true;
}
/**
* Get the displayable name of the attribute.
*
* @param string $attribute
*
* @return string
*/
protected function getAttribute($attribute)
{
// `group.names.0` becomes `group[name][0]`
if (str_contains($attribute, '.')) {
$attribute = $this->dotToArrayString($attribute);
}
return parent::getAttribute($attribute);
}
/**
* Add an error message to the validator's collection of messages.
*
* @param string $attribute
* @param string $rule
* @param array $parameters
*
* @return void
*/
protected function addError($attribute, $rule, $parameters)
{
// `group.names.0` becomes `group[name][0]`
if (str_contains($attribute, '.')) {
$attribute = $this->dotToArrayString($attribute);
}
return parent::addError($attribute, $rule, $parameters);
}
/**
* Convert dot notation array to an array string used by html form inputs.
*
* fx: `group.names.0` becomes `group[name][0]`
*
* @param $attribute
*
* @return string
*/
protected function dotToArrayString($attribute)
{
$segments = explode('.', $attribute);
$first = array_shift($segments);
$segments = array_map(
function ($segment) {
return '[' . $segment . ']';
},
$segments
);
return $first . implode('', $segments);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment