Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating fields as unique in cakephp 3.0

How do you validate a field is unique in cakephp 3.0? There doesn't appear to be a validation function listed in the API.

like image 742
GatorGuy023 Avatar asked Jul 11 '15 03:07

GatorGuy023


2 Answers

You want to use the rule validateUnique. For example, to check an email address is unique on an UsersTable:-

public function validationDefault(Validator $validator)
{
    $validator->add(
        'email', 
        ['unique' => [
            'rule' => 'validateUnique', 
            'provider' => 'table', 
            'message' => 'Not unique']
        ]
    );

    return $validator;
}

Details can be found in the API docs.

like image 138
drmonkeyninja Avatar answered Oct 17 '22 13:10

drmonkeyninja


you have to use the rules from cake's ORM on your table...

add this at the top of your UsersTable after your namespace

use Cake\ORM\Rule\IsUnique;

Then prepare your rule to apply to your field by placing it in a public function

public function buildRules(RulesChecker $rules){
        $rules->add($rules->isUnique(['email']));
        return $rules;
    }

Consult the cakephp documentation for more information about RULES

like image 6
Rod Avatar answered Oct 17 '22 14:10

Rod