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

Laravel 9 CRUD编辑报错:Attempt to read property 'name' on null

问题解决:Laravel CRUD编辑功能中"Attempt to read property 'name' on null"错误

这个错误的核心是视图中的$testimoni变量为null,导致无法读取name属性,下面逐一排查并解决你的代码问题:

1. 列表页编辑链接路径错误

你的index.blade.php中生成的编辑URL存在重复的/edit,导致路由无法正确传递ID参数,控制器无法找到对应数据:
错误代码:

<a href="{{ url('/admin/testimonial/edit' . $testi->id .'/edit')}}">...</a>

修正为(推荐使用路由命名生成URL,更可靠):

<a href="{{ route('testimonial.edit', $testi->id) }}">
    <button type="button" class="btn btn-block bg-gradient-danger btn-sm">
        <i class="fas fa-edit"></i>
    </button>
</a>

或者用原生URL写法:

<a href="{{ url('/admin/testimonial/' . $testi->id . '/edit') }}">...</a>

2. 控制器传递的变量名与视图使用不一致

控制器中通过->with('testimonial', $testimoni)将变量命名为testimonial传递给视图,但你在edit.blade.php中使用的是$testimoni->name,两者不匹配:
修正方法二选一:

  • 调整控制器,传递变量名为testimoni:
public function edit($id)
{
    $testimoni = Testimoni::find($id);
    return view('admin.testimonial.edit')->with('testimoni', $testimoni);
}
  • 或者调整视图,使用控制器传递的$testimonial变量:
<input type="text" class="form-control" id="name" name="name" value="{{$testimonial->name}}">

3. 表单提交路由缺失参数

edit.blade.php中的表单提交路由route('testimonial.update')缺少必要的ID参数,resource路由的update方法需要传入对应数据的ID:
修正为(根据你最终使用的变量名调整,比如用$testimoni->id或$testimonial->id):

<form action="{{ route('testimonial.update', $testimoni->id) }}" method="post">

4. 优化数据查询避免null

建议在控制器中使用findOrFail()替代find(),这样当ID不存在时会直接返回404页面,避免将null传递到视图引发错误:

public function edit($id)
{
    $testimoni = Testimoni::findOrFail($id);
    return view('admin.testimonial.edit')->with('testimoni', $testimoni);
}

内容的提问来源于stack exchange,提问作者witch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:27:24