Check fields as unique in cakephp 3.0

How do you check a field uniquely in cakephp 3.0? There is no validation function in the API.

+5
source share
4 answers

You want to use the validateUnique rule. For example, to check the email address is unique on 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 .

+13
source

you should use the rules from Cake ORM in your table ...

add this at the top of your UsersTable account after your namespace

 use Cake\ORM\Rule\IsUnique; 

Then prepare your rule to apply to your field by placing it in an open function

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

Refer to cakephp documentation for more information on RULES

+3
source

Validation providers can be objects or class names. If a class name is used, methods must be static. To use a provider other than "default", be sure to set the provider key in your rule:

 // Use a rule from the table provider $validator->add('title', 'unique', [ 'rule' => 'uniqueTitle', 'provider' => 'table' ]); 

For more information, see Adding Verification Providers in the CakePHP3 Reference.

+1
source

Use the application rules described in the manual .

0
source

All Articles