Laravel使用update()更新数据库记录失败,求排查与正确用法
Laravel update()方法未更新数据库问题排查与正确用法
问题现状
执行代码后仅显示成功提示,但数据库记录未更新,对应代码如下:
Controller代码
public function updateTeachers(Request $request, User $teachers){ $validated = $request->validate([ "name" => ['required'], "email" => ['required'], ]); $teachers->update($validated); return back()->with('information-message', 'Data was successfully updated'); }
View代码
<form action="/teacher/{{ $dataTeacher->id }}" method="POST" class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-80 px-4 py-3"> @method('PUT') @csrf <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full px-3"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="grid-first-name"> Name </label> <input type="text" name="name" value="{{ $dataTeacher->name }}" class="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white focus:border-gray-500" required> </div> </div> <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full px-3"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="grid-password"> Email </label> <input type="email" name="email" value="{{ $dataTeacher->email}}" class="appearance-none block w-full bg-gray-200 text-gray-700 border border-gray-200 rounded py-3 px-4 mb-3 leading-tight focus:outline-none focus:bg-white focus:border-gray-500" required> </div> </div> <button type="submit" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Push</button> </form>
Route代码
Route::put('/teacher/{teacher}', [UserController::class, 'updateTeachers']);
代码错误分析
路由模型绑定参数不匹配
路由占位符是{teacher},但Controller方法的参数名是$teachers,Laravel路由模型绑定严格匹配参数名,这会导致无法正确注入目标User模型实例,你实际操作的是一个空模型对象,自然不会更新数据库。批量赋值未授权
检查User模型,确保name和email字段在$fillable属性中声明,或者设置$guarded = []。Laravel默认开启批量赋值保护,未授权的字段无法通过update()方法批量更新。邮箱验证缺少唯一规则(可选但重要)
如果允许修改邮箱,需添加unique规则并排除当前用户ID,避免邮箱重复报错:
"email" => ['required', 'email', Rule::unique('users')->ignore($teachers->id)]
记得引入use Illuminate\Validation\Rule;。
Laravel update()方法正确用法
确保模型实例正确获取
- 路由模型绑定:保证路由占位符和方法参数名一致,比如路由
{teacher}对应参数User $teacher,Laravel会自动根据ID查找并注入模型实例。 - 手动查找:若不用路由绑定,需手动获取模型:
$teacher = User::findOrFail($request->id);
- 路由模型绑定:保证路由占位符和方法参数名一致,比如路由
处理批量赋值
在模型中声明可填充字段:
class User extends Model { protected $fillable = ['name', 'email']; // 或者设置$guarded为空数组,允许所有字段批量赋值 // protected $guarded = []; }
- 调用update()方法
直接传入验证后的数组即可完成批量更新:
$teacher->update($validated); // 也可手动赋值后调用save() $teacher->name = $validated['name']; $teacher->email = $validated['email']; $teacher->save();
- 验证与异常处理
添加合法的验证规则,更新后返回反馈信息,同时可捕获异常处理更新失败场景:
try { $teacher->update($validated); return back()->with('information-message', 'Data was successfully updated'); } catch (\Exception $e) { return back()->with('error-message', 'Failed to update data: ' . $e->getMessage()); }
内容的提问来源于stack exchange,提问作者Cloud Strife
相关产品推荐
相关产品推荐

