LoginSignup
14
10

More than 5 years have passed since last update.

【Laravel】フォームリクエストFormRequestでバリデーション前に入力値(Request)を整える

Posted at

ValidatesWhenResolvedTrait.phpprepareForValidation()をオーバーライドすると、バリデーション実行前にリクエストに対して任意の処理を行い、データを整形できます:relaxed:

/app/Http/Requests/MyFormRequest.php

    protected function prepareForValidation(): void
    {
        // ここで任意の処理を行う
        // 今回は、comment配列から、空の配列要素を取り除く処理を行う例
        if ($this->has('comment')) {
            $this->merge([
                'comment' => $this->trimEmptyElements(
                    $this->input('comment')
                )
            ]);
        }
    }

バリデーション前に入力値に任意の処理を行いたいことって結構ありますよね:blush:
以下オーバーライド元の処理を参考に掲載しておきます:dizzy:

参考

14
10
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
14
10