3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravelで複雑なValidationをやりたい時のFormRequest

Last updated at Posted at 2021-03-29

概要

DB接続なども織り交ぜた複雑なValidationをやりたい時、最近忘れがちなので備忘録として。

前提

  • Laravel5.5~6.xで確認

実装

HogeRequest.php
.
.
.

class HogeRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }


    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'fuga_id' => [
                'required',
                function ($attribute, $value, $fail) {
                    // ここにロジックを書く
                    $fuga = Fuga::find($this->input('fuga_id'));

                    if ($fuga !== null) {
                        return $fail('fugaをすでにしています');
                    }
                },
            ],
        ];
    }

解説

  • rulesにfunction ($attribute, $value, $fail) {}を使用することで、複雑なValidationを表現できる
  • $this->input({$name})で値を取得できる
  • return $fail({$message})でValidation失敗時のメッセージを返却できる

参照

すみません。ブックマークし忘れてしまいました...

3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?