Laravel 8 CRUD更新功能提交按钮失效、organisation_id为空问题咨询
问题根因与修复方案
核心错误点
- 表单嵌套:Blade模板中你已经定义了外层的普通form标签,在组织下拉框位置又调用了
Form::open()生成了第二个表单,HTML不允许表单嵌套,这是点击提交按钮无响应的直接原因。浏览器会将提交按钮识别为内层无提交地址表单的元素,点击后不会触发提交动作也不会报错。 - 下拉框参数错误:
- 下拉框的
name属性设置为id,与控制器需要接收的organisation_id不匹配,导致后端拿不到组织ID,最终存为NULL - 控制器中查询组织列表时只pluck了组织名称,下拉选项的value值为组织名而非组织ID,即使拿到值也不符合数据库字段要求
- 姓名输入框未闭合,缺少末尾的
>标签
- 下拉框的
- 验证规则可优化:现有验证只判断必填,可补充
exists规则验证组织ID是否真实存在于组织表中,避免非法数据入库
修复代码
1. 控制器edit方法
public function edit($id) { $record = User::findOrFail($id); // pluck第二参数指定键为组织ID,后续下拉选项的value就会自动使用组织ID $orgList = Organisation::pluck('name', 'id'); return view ('user.edit',compact('record','orgList')); }
2. Blade编辑页模板
<div class="card"> <div class="card-body"> <form action="{{route('user_edit_store1', $record->id)}}" method="POST"> @csrf <div class="form-group row"> <label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Name') }}</label> <div class="col-md-6"> <input id="name" type="text" class="form-control @error('name') is-invalid @enderror" name="name" value="{{ old('name', $record->name) }}" > @error('name') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row"> <label for="organisation_id" class="col-md-4 col-form-label text-md-right">{{ __('Organisation') }}</label> <div class="col-md-6"> {{-- 删掉多余的Form::open,修改下拉name为organisation_id,默认值选中当前用户的组织ID --}} {!! Form::select('organisation_id', $orgList, $record->organisation_id, ['class' => 'form-control', 'id' => 'organisation_id']) !!} @error('organisation_id') <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong> </span> @enderror </div> </div> <div class="form-group row mb-0"> <div class="col-md-6 offset-md-4"> <button type="submit" class="btn btn-primary" > {{ __('Save') }} </button> </div> </div> </form> </div> </div>
3. 控制器edit_store方法(可选优化)
public function edit_store(Request $request, $user) { $validated = $request->validate([ 'name' => 'required', // 补充exists验证,确保提交的组织ID真实存在 'organisation_id' => 'required|exists:organisations,id', ]); $record = User::findOrFail($user); // 已经配置$fillable的情况下可直接用update方法简化代码 $record->update($validated); return redirect ('user')->with('success', 'Thank you'); }
关于数据验证的疑问
更新函数没有强制要求必须做数据验证,但所有涉及用户输入的操作都强烈建议加验证:验证可以过滤非法输入、避免脏数据入库、提前拦截不符合业务规则的请求,降低后续业务逻辑出错的概率。如果你的业务要求用户必须关联组织,去掉验证后就会出现用户提交空组织ID也能入库的问题,破坏业务逻辑的完整性。
内容的提问来源于stack exchange,提问作者Aiman Nazri
相关产品推荐
相关产品推荐

