我目前正在為我的專案使用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
uj5u.com熱心網友回復:
當您詢問獨特規則的排序時。唯一規則的(未記錄的)格式是:
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 一起使用以防止重復。
希望答案有幫助
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/429177.html
上一篇:驗證時嵌套的Joi
