6
4

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 5 years have passed since last update.

Laravelのバリデーションで自分自身の重複は無視したいとき

Posted at

Laravelのバリデーターで重複を許さないよう定義している状態で、自分自身のデータを書き換えようとしたらバリデーションに引っかかって「ひえ〜」ってなった事はありませんか?

$validatedData = $request->validate([
    'name' => 'required|string|max:255',
    'email' => ['required','string','email','max:255','unique:users'],
    'password' => 'required|string|min:8',
]);

無視したい項目をignoreで指定することで解決できます。

$validatedData = $request->validate([
    'name' => 'required|string|max:255',
    'email' => ['required','string','email','max:255', Rule::unique('users')->ignore(Auth::id())],
    'password' => 'required|string|min:8',
]);

よくある「マイページで自分のプロフィール情報を変えたい」という時にはAuth::id()でログイン中のユーザーIDを取り出したら簡単ですね。

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?