我目前正在为我的项目使用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