You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 12:39:01