Skip to content

Instantly share code, notes, and snippets.

@andrewandante
Last active April 9, 2018 13:00
Show Gist options
  • Save andrewandante/04337042642d99adb6496b967ca17801 to your computer and use it in GitHub Desktop.
Save andrewandante/04337042642d99adb6496b967ca17801 to your computer and use it in GitHub Desktop.
Validate a unique DB Field
public function validate()
{
$result = parent::validate();
$this->ensureUnique('Title', $result);
return $result;
}
/**
* @param string $fieldName
* @param \ValidationResult $validationResult
*
* @return \ValidationResult
*/
protected function ensureUnique($fieldName, &$validationResult)
{
if ($this->isChanged($fieldName)) {
$exists = myClass::get()->filter($fieldName, $this->getField($fieldName))->first();
if ($exists) {
$validationResult->error($fieldName.' must be unique among '. myClass::class);
}
}
return $validationResult;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment