How to use laravel validation rule in custom validation rule?

I have an input $data =['identifier' = 'xxxxxxxxxx']; and I want to save encrypt($data['identifier']) in the info primary id column.

I have to check before saving it. The rule unique:info, id does not fit here, so I want to write a user check rule. And in the custom validation rule, I encrypt() value first, then use the unique validation rule.

I know how to write a custom validation rule, but how to use the unique validation rule in my custom validation rule?

+5
source share
2 answers

The "unique" and "exists" rules use the DatabasePresenceVerifier class. That way, you don’t really need to extend the unique rule, just access this presence verifier. For instance:

 Validator::extend('encrypted_unique', function ($attribute, $value, $parameters, $validator) { list ($table, $column, $ignore_id) = $parameters; // or hard-coded if fixed $count = $validator->getPresenceVerifier()->getCount($table, $column, encrypt($value), $ignore_id); return $count === 0; }); 

Then you can use it as usual:

 'identifier' => "encrypted_unique:table,column,$this_id" 
+2
source

Suppose you have an A ModuleRequest that checks your inputs, you can write this method in this class

 protected function validationData() { $all = parent::validationData(); $all['email'] = encrypt($all['email']); return $all; } 
+1
source

Source: https://habr.com/ru/post/1269279/


All Articles