T
T
TAnonim2018-07-14 20:59:20
Laravel
TAnonim, 2018-07-14 20:59:20

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!');
        }
    });
}

In what class should this function be defined and what does this feature do in general? On enSO they say that this is necessary for code reuse, but it's still not entirely clear to me.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton, 2018-07-15
@Yadalay

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 question

Ask a Question

731 491 924 answers to any question