Laravel 4 Валидация уникальная (база данных) игнорирует ток
Я делаю проверку на форме редактирования пользователей и проверяю проверку, если имя пользователя уникально в базе данных или нет.
Однако, когда редактирование пользователя и вы не изменяете поле имени пользователя, оно все еще проверяет, является ли это поле уникальным или нет...
Есть ли способ laravel игнорировать текущее имя пользователя, если оно не изменено?
Ответы
Ответ 1
Должен прочитать документы больше, конечно же, laravel 4 делает это...
Что я имел
$rules = array('username' => 'required|unique:users');
Что у меня
$rules = array('username' => 'required|unique:users,username,'.$id);
Вы можете сказать валидатору игнорировать данный идентификатор, как указано выше.
Ответ 2
Это решение работало для меня:
protected $rules = array(
'email' => "required|email|unique:users,email,:id",
);
Ответ 3
Для Laravel 4.1, если вы расширяете класс Illuminate\Validation\Validator
, переопределите метод validateUnique()
как таковой:
/**
* Validate the uniqueness of an attribute value on a given database table.
*
* If a database column is not specified, the attribute will be used.
*
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @return bool
*/
protected function validateUnique($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'unique');
$table = $parameters[0];
// The second parameter position holds the name of the column that needs to
// be verified as unique. If this parameter isn't specified we will just
// assume that this column to be verified shares the attribute name.
$column = isset($parameters[1]) ? $parameters[1] : $attribute;
// If the specified ID column is present in the data, use those values; otherwise,
// fall back on supplied parameters.
list($idColumn, $id) = [null, null];
if (isset($parameters[2])) {
list($idColumn, $id) = $this->getUniqueIds($parameters);
if (strtolower($id) == 'null') $id = null;
else if (strtolower($id) == 'id' && isset($this->data[$idColumn])) $id = $this->data[$idColumn];
}
else if (isset($this->data['id'])) {
$idColumn = 'id';
$id = $this->data[$idColumn];
}
// The presence verifier is responsible for counting rows within this store
// mechanism which might be a relational database or any other permanent
// data store like Redis, etc. We will use it to determine uniqueness.
$verifier = $this->getPresenceVerifier();
$extra = $this->getUniqueExtra($parameters);
return $verifier->getCount(
$table, $column, $value, $id, $idColumn, $extra
) == 0;
}
В ваших правилах валидатора вы можете это сделать (проверит поле id
, существующее в данных проверки - это наиболее обобщенное использование):
$rules = 'unique:model,field';
this (будет проверять поле id
, существующее в данных проверки) (эквивалентно приведенному выше):
// specifying anything other than 'id' or 'null' as the 3rd parameter
// will still use the current behavior
$rules = 'unique:model,field,id';
или это (проверит поле idColumn
, существующее в данных проверки):
// specifying anything other than 'id' or 'null' as the 3rd parameter
// will still use the current behavior
$rules = 'unique:model,field,id,idColumn';
Ответ 4
Привет, вы можете использовать валидатор в качестве службы или скопировать логику и применить эту потребность, как это
$valitator = MyCustomValidator::make()->on('update')->setCurrent($id);
зарегистрируйтесь:
https://github.com/bradleySuira/laravel-context-validator/blob/master/examples/unique-on-update.php