Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use laravel's validation rule in custom validation rule?

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?

like image 439
LF00 Avatar asked Jun 28 '17 03:06

LF00


People also ask

What is the method used for specifying custom message for validation errors in form request?

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.

What method should you implement for your custom validator in laravel?

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.

What is the method used to configure validation rules in form request laravel?

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.


2 Answers

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"
like image 124
alepeino Avatar answered Nov 14 '22 23:11

alepeino


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;

}
like image 27
wahdan Avatar answered Nov 14 '22 23:11

wahdan