LoginSignup
2
1

More than 5 years have passed since last update.

フォームリクエストへのAfterフックを追加 (Laravel5.1)

Last updated at Posted at 2017-04-17

Laravel5.4では以下の様に、フォームリクエストへのAfterフックを追加する方法がドキュメントで紹介されている。
参考:https://laravel.com/docs/5.4/validation#form-request-validation

/**
 * Configure the validator instance.
 *
 * @param  \Illuminate\Validation\Validator  $validator
 * @return void
 */
public function withValidator($validator)
{
    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });
}

Laravel5.1でも同じ機能を使いたかったので以下のように実装した。

public function getValidatorInstance()
{
    $validator = parent::getValidatorInstance();

    $validator->after(function ($validator) {
        if ($this->somethingElseIsInvalid()) {
            $validator->errors()->add('field', 'Something is wrong with this field!');
        }
    });

    return $validator;
}

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1