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 验证规则的简短方法来做到这一点。
https://laravel.com/docs/9.x/validation#available-validation-rules

4

1 回答 1

1

当您询问独特规则的排序时。唯一规则的(未记录的)格式是:

table[,column[,ignore value[,ignore column[,where column,where value]...]]]

注意::可以指定多个“where”条件,但只能检查相等性。任何其他比较都需要一个闭包(如已接受的答案)。

但不推荐。而是使用闭包以获得更好的选项和可读性。

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

并分别处理错误信息

据我了解,您正在尝试处理可能的任何 slug->name、slug->slug、name->slug、name->name 对话的唯一性,在这种情况下,我建议将 uid/UUID 与 slug 一起使用以防止重复。

希望答案有帮助

于 2022-02-17T05:56:24.697 回答