I have input $data =['identifier' = 'xxxxxxxxxx'];
, and want to save the encrypt($data['identifier'])
to the table info
primary id
column.
I've to validate before save it. Rule unique:info, id
isn't suitable here, so I want to write a custom validation rule. And in the custom validation rule, I encrypt()
the 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?
After checking if the request failed to pass validation, you may use the withErrors method to flash the error messages to the session. When using this method, the $errors variable will automatically be shared with your views after redirection, allowing you to easily display them back to the user.
You should add all your validation logic in the passes() function. It should return true or false based on the logic you have written in the function. The message() function returns a string that specifies the error message to be displayed in case the validation fails.
Laravel Form Request class comes with two default methods auth() and rules() . You can perform any authorization logic in auth() method whether the current user is allowed to request or not. And in rules() method you can write all your validation rule.
Rules "unique" and "exists" use the DatabasePresenceVerifier class. So, you don't need to really 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"
Suppose you have A ModuleRequest that validates your inputs,you can write this method in this class
protected function validationData()
{
$all = parent::validationData();
$all['email'] = encrypt($all['email']);
return $all;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With