Laravel Form Request更新时unique字段校验如何忽略当前记录ID
问题解决方案
错误原因
- 你在FormRequest中尝试获取的
id是路由路径上的参数,不属于请求body/query参数,不能用$this->request->get('id')获取,导致取值为空 - 原代码存在语法错误:
$id = $this->request->get('id') ? ',.' $this->request->get('id') : '';缺少字符串拼接符,且逗号后多写了无用的点符号 - 数组追加赋值逻辑错误:
$rules += ['title' => xxx]不会覆盖原有title键的规则,更新场景下的校验规则不会生效
修复后的代码
1. ParentCategoryRequest的rules方法
public function rules() { $rules = [ 'title' => 'required|min:3|unique:parent_categories' ]; // 匹配更新请求方法 if (in_array($this->getMethod(), ['PUT', 'PATCH'])) { // 从路由参数中获取id $id = $this->route('id'); // 直接覆盖title的校验规则 $rules['title'] = 'required|min:3|unique:parent_categories,title,' . $id; } return $rules; }
如果路由用了模型绑定(路由定义为Route::put('/parent-categories/{parentCategory}', [xxx::class, 'update'])),还可以加上软删除过滤规则,避免已删除的记录影响校验:
$rules['title'] = 'required|min:3|unique:parent_categories,title,' . $this->route('parentCategory')->id . ',id,deleted_at,NULL';
2. 控制器代码优化
public function update(ParentCategoryRequest $request, $id) { DB::beginTransaction(); try { $parentCategory = ParentCategory::findOrFail($id); // 用validated()获取经过校验的合法数据,避免批量赋值风险 $parentCategory->update($request->validated()); DB::commit(); // 更新操作默认返回200状态码更符合规范,201为创建资源的专用返回码 return $this->success('Parent category updated successfully', new ParentCategoryResource($parentCategory), 200); } catch (Exception $e) { DB::rollBack(); return $this->error($e->getMessage(), $e->getCode()); } }
内容的提问来源于stack exchange,提问作者Dibbya
相关产品推荐
相关产品推荐

