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

RequestクラスでRule::uniqueを用いたバリデーション実装について

Posted at

テーブル名.カラム名で絞り込みをしたときに、カラムの値が重複したときに重複エラーのバリデーションを返却したいときがあります。

今回は、Laravel側でRequestクラスを用いた実装方法を例にサンプルコードを用意しました。

作成したRequestクラス

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'email' => [
                'required',
                'email',
                Rule::unique('users', 'email')->where(function ($query) => 
                    $query->where('status', 'active')
                ),
            ],
        ];
    }

    public function messages(): array
    {
        return [
            'email.unique' => 'このメールアドレスはすでに使用されています。',
        ];
    }
}

簡単な実装解説

Rule::unique('テーブル名', 'カラム名') の書き方で、指定したテーブル・カラムの値が既存レコードに存在しないか確認します。

where で条件付きユニークチェックを行い、例えば「status が active の行だけ重複しないようにしたい」という場合に便利です。

messages() でエラーメッセージも定義することができます。

まとめ

条件付きのユニークチェックをしたいとき、上記の実装でほぼ解決できます。
メールアドレスなど重複を避けたい場合、非常に便利です。
今回は私が過去に実装したコードを要約して、忘備録としてまとめました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?