LoginSignup
0
0

More than 1 year has passed since last update.

Laravelで他フィールドが特定の値だった場合にバリデーションしたい

Posted at

やりたいこと

以下のリクエストパラメータがあるとする

site_kinds(サイト種別) site_url(サイトURL)
例:yahoo,google,bing 例:google.co.jp/abc,yahoo.co.jp/def
必須項目、yahoo,google,bingのどれかであることをバリデーション googleだった場合のみURLが重複登録されていないことを確認

環境

Laravel 9.x

Laravelでデフォルトで用意しているメソッドを使ってみる

公式:https://readouble.com/laravel/9.x/ja/validation.html

「他のフィールドが特定の値と一致した場合」にできそうなバリデーションは何個かある

  • 空かどうか
  • nullかどうか
  • requiredにする
  • validate,validatedから除外する

validate,validatedから除外するを採用

// site_urlsというテーブルには「site_url,site_kind」のカラムがある前提
'site_url' => ['exclude_unless:site_kinds,google', 'required', 'url',
     Rule::unique('site_urls', 'site_url')->where('site_kind', 'google')->whereNull('deleted_at')]
0
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
0
0