validationcakephpcakephp-3.xvalidationrule

cakephp 3 add unique constraint


I tried the following to add a unique validation rule to my model:

$validator
            ->requirePresence('pseudonym', 'create',['rule' => 'isUnique'])
            ->notEmpty('pseudonym');

Now I don't get any errors. If I add a database-constraint I only get a database-error:

Integrity constraint violation: 1062 Duplicate entry 'Stella' for key 'pseudonym'

If I add:

$validator
        ->add('pseudonym','unique',['rule' => 'validateUnique']);

I get the following exception:

Method validateUnique not found

So how does it work with cakephp 3?


Solution

  • CakePHP has a Rule class that allows you to define unique fields http://book.cakephp.org/3.0/en/orm/validation.html#creating-unique-field-rules

    use Cake\ORM\Rule\IsUnique;
    
    // A single field.
    $rules->add($rules->isUnique(['email']));
    
    // A list of fields
    $rules->add($rules->isUnique(['username', 'account_id']));