0

現在、プロジェクトにLaravel 9を使用しています。

ここに私の検証ルールがあります

public function rules()
{
    $parent_id = $this->parent_id != 0 ? $this->parent_id : null;

    return [
        'name' => [
            'required', 'string', 'min:2', 'max:50', function ($attribute, $value, $fail) use ($parent_id) {

                $categories = Category::select(['id', 'parent_id', 'name'])
                    ->where('parent_id', $parent_id)
                    ->where('id', '<>', $this->route('category')?->id) // for update
                    ->get();

                foreach ($categories as $row) {

                    if (str($row->name)->lower() == str($value)->lower()) {

                        $fail('The ' . $attribute . ' has already been taken.');

                    } elseif (str($row->name)->slug() == str($value)->slug()) {

                        $fail('The ' . $attribute .  ' slug matches another.');

                    }
                }
            }
        ],

        // more..
    ];
 }

Laravel Validation Rules を使用してこれを行う簡単な方法はありますか。
https://laravel.com/docs/9.x/validation#available-validation-rules

4

1 に答える 1

1

おっしゃる通り独自ルールのソートハンド。一意のルールの (文書化されていない) 形式は次のとおりです。

テーブル[、列[、値を無視[、列[、列、値]を無視...]]]

注:: 複数の「where」条件を指定できますが、等値のみをチェックできます。他の比較には、(受け入れられた回答のように) クロージャーが必要です。

しかし、お勧めしません。むしろ、より良いオプションと読みやすさのために閉鎖を使用してください。

Rule::unique('categories')
      ->where('parent_id', $parent_id)
      ->where(function ($sql) use ($request) {
          $sql->where('name', $request->name)
              ->orWhere('slug', $request->name);
       })

エラーメッセージを個別に処理する

私が理解している限り、スラッグ->名前、スラッグ->スラッグ、名前->スラッグ、名前->名前の会話の一意性を処理しようとしています。その場合、スラッグでuid / UUIDを使用することをお勧めします重複を防ぐため。

答えが役立つことを願っています

于 2022-02-17T05:56:24.697 に答える