Laravel 8更新博客文章出现'Creating default object from empty value'错误是什么原因
这个错误是因为执行$data = Post::find($request->id);时没有找到对应ID的文章,$data为null,后续给null对象赋值属性就触发了该报错。
修复步骤
1. 调整控制器逻辑
- 用
findOrFail替代find,找不到数据时直接抛出404错误,避免返回空值 - 修正数据保存逻辑:赋值属性后调用
save()方法,或者直接用update()传入更新数组
修改后的控制器代码:
public function update(Request $request, $id = null) { // 优先取路由参数的ID,没有就取请求参数的ID $post = Post::findOrFail($id ?? $request->id); $post->title = $request->input('title'); $post->description = $request->input('description'); $post->save(); return redirect('/index')->with('message', 'successfully published'); }
如果用update写法更简洁:
public function update(Request $request, $id = null) { $post = Post::findOrFail($id ?? $request->id); $post->update($request->only(['title', 'description'])); return redirect('/index')->with('message', 'successfully published'); }
2. 调整路由配置(两种方案二选一)
方案A:POST路由增加ID参数(推荐,符合RESTful规范)
Route::get('posts/edit/{post}',[PostController::class,'edit']); Route::post('/update/{post}',[PostController::class,'update']);
对应编辑页面的表单提交action写为/update/{{$post->id}}即可。
方案B:表单增加隐藏ID字段
如果不修改路由,就在编辑页的表单里增加隐藏域:
<input type="hidden" name="id" value="{{$post->id}}">
确保提交时会把文章ID传到$request->id里。
内容的提问来源于stack exchange,提问作者Saumil Joshi
相关产品推荐
相关产品推荐

