I was talking to Matthew Pennell about his new RoR hobby and he was saying that one little bit he appreciated was how easy rails makes it to validate_uniqueness.
I tried to add a unique method to the cake validation core, but the level of separation between the Model & the validation classes was beyond me.
So….here is the code for your model:
var $validate = array(
'email' =>array('rule' =>array('_isUnique', 'email'))
);
Where every instance of “email” in the above code should be replaced with the fieldname that you wish to validate as unique.
Then put the following code in your AppModel class (app_model.php in your app folder.) If app_model.php does not exist in your application, copy the one found at cake/console/libs/templates/skel into your own app directory.
/** * Checks that a value is unique * * @param string $check Value to check * @param string $field Field to check for value * @return boolean Success * @access public */ function _isUnique($check, $field) { $conditions = array(); foreach($check as $c) { $conditions[] = "$this->name.$field=\"" . addslashes($c) . "\""; }if(isset($this->data[$this->name][‘id’])){ $conditions[] = "$this->name.id<>\"".addslashes($this->data[$this->name]['id'])."\""; }$results = $this->find($conditions);if(!empty($results)) { return false; } else { return true; } }
(Fixed thanks to Ambiguator’s comment)
You should not need to change this function. I am grabbing anything that is specific to your model, from your application (and class instance).

Are people using this? Apparently it’s #1 when searching for cakephp validate uniqueness
Bah.
— Walker Hamilton · Sep 17, 03:41 PM · #
Yeah easy to find this script.
But something wrong with cakephp 1.1.17,
@ Warning: preg_match() expects parameter 1 to be string, array given in /cake/libs/model/model_php5.php on line 1359 @
Seems that cake wants to preg_match only
— esion · Sep 20, 04:26 AM · #
ok waiting for cakephp 1.2
— esion · Sep 20, 04:29 AM · #
All of the cake work I do is in 1.2. Sorry, caveat.
— Walker Hamilton · Sep 20, 06:41 AM · #
I’m using cake1.2
this function did not work for me.
first off, $check is an array, so you can’t addslashes($check), you have to loop through it and build the conditions first.
here is a version that worked for me – sorry about the poor formatting.
— ambiguator · Feb 15, 09:16 AM · #
Thanks mate – works well when I use the changes suggested by ambiguator.
— Ben · Aug 17, 10:03 PM · #