Laravel CRUD应用更新功能报错:尝试为null赋值属性"PName"
问题分析与解决方案
核心问题
报错Attempt to assign property "PName" on null的根源是:
- 表单里的
update_id输入框设置了disabled属性,禁用的表单元素不会被提交到服务器,导致控制器中$req->get('update_id')获取到的值为null - 执行
product::find($ID)时,传入null会生成SQL:select * fromproductswhereproducts.Idis null limit 1,找不到对应记录返回null - 后续尝试给
null对象赋值属性,触发报错
修复步骤
1. 修复表单提交的ID问题
禁用的输入框无法提交数据,需修改表单中的update_id输入框,二选一即可:
方案一:改用readonly(推荐)
将disabled替换为readonly,既保留不可编辑的特性,又能正常提交数据:
<div class="mb-2"> <label for="">Product ID</label> <input type="text" class="form-control" value="{{$pid}}" name="update_id" readonly> </div>
方案二:保留disabled并添加隐藏输入框
保留原禁用输入框用于展示,新增隐藏输入框传递ID值:
<div class="mb-2"> <label for="">Product ID</label> <input type="text" class="form-control" value="{{$pid}}" disabled> <input type="hidden" name="update_id" value="{{$pid}}"> </div>
2. 增加控制器的异常处理
为避免找不到对应记录时出错,可在控制器中添加判断或使用findOrFail:
方式一:使用findOrFail(Laravel推荐)
找不到记录时自动抛出404异常:
function update(Request $req){ $ID = $req->get('update_id'); $Name = $req->get('update_name'); $Price = $req->get('update_price'); $new_prod = product::findOrFail($ID); $new_prod->PName = $Name; $new_prod->PPrice = $Price; $new_prod->save(); return redirect('/'); }
方式二:手动判断并返回错误提示
function update(Request $req){ $ID = $req->get('update_id'); $Name = $req->get('update_name'); $Price = $req->get('update_price'); $new_prod = product::find($ID); if (!$new_prod) { return back()->with('error', '该产品不存在'); } $new_prod->PName = $Name; $new_prod->PPrice = $Price; $new_prod->save(); return redirect('/'); }
3. 优化表单请求方法(可选)
更新操作建议使用POST或PUT方法(符合REST规范),修改表单:
<form action="updatedata" method="post"> @csrf @method('PUT') <!-- 如果用PUT方法,需要添加这个隐藏字段 --> <!-- 其余表单内容不变 --> </form>
同时在路由中对应配置PUT请求的路由。
内容的提问来源于stack exchange,提问作者Ashir Mustafa
相关产品推荐
相关产品推荐

