Answer the question
In order to leave comments, you need to log in
What is the purpose of after hook in laravel Form Request?
Greetings. The documentation has a section about after hooks with the following example:
public function withValidator($validator)
{
$validator->after(function ($validator) {
if ($this->somethingElseIsInvalid()) {
$validator->errors()->add('field', 'Something is wrong with this field!');
}
});
}
Answer the question
In order to leave comments, you need to log in
In order to add your own rules and display validation error messages. Here is an example:
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'current_password' => 'required_with:password',
'password' => 'required_with:current_password|confirmed',
'name' => 'required|unique:users,name,' . $this->user()->id
];
}
/**
* Configure the validator instance.
*
* @param \Illuminate\Validation\Validator $validator
* @return void
*/
public function withValidator($validator)
{
$validator->after(function ($validator) {
$currentPassword = $this->current_password;
if (! empty($currentPassword) && ! Hash::check($currentPassword, $this->user()->password)) {
$validator->errors()->add('current_password', 'Текущий пароль не совпадает с указанным паролем.');
}
if (! empty($currentPassword) && ! strcmp($currentPassword, $this->password)) {
$validator->errors()->add('password', 'Новый пароль не может совпадать с текущим паролем.');
}
if (! empty($this->password) && mb_strlen($this->password) < 6) {
$validator->errors()->add('password', 'Пароль должен содержать минимум 6 символов.');
}
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question