Laravel Eloquent关联报错:Trying to get property of non-object求助
解决Laravel评论关联用户报错的问题
咱们先拆解下你遇到的问题根源:
评论未正确关联核心字段(或模型未配置可填充属性)
你在store方法里创建Comment实例时,只传递了body参数,但既没关联当前文章的post_id,也没确保Comment模型允许批量赋值这些字段——这会导致user_id或post_id无法正确写入数据库,最终让$comment->user返回null,直接访问name属性就会抛出Trying to get property of non-object错误。模板未做容错处理
就算关联逻辑修复完成,也可能存在用户被删除的极端情况,此时$comment->user依然会是null,直接访问属性还是会报错。
分步解决方案:
第一步:更新Comment模型,配置可填充字段
打开Comment.php,添加$fillable属性,允许批量赋值的字段:
class Comment extends Model { protected $fillable = ['body', 'user_id', 'post_id']; // 你的关联方法保持不变 public function post() { return $this->belongsTo(Post::class); } public function user() { return $this->belongsTo(User::class); } }
第二步:修正CommentsController的store方法
推荐用更简洁的方式,通过文章的关联关系创建评论,这样会自动填充post_id,同时手动指定当前登录用户的user_id:
public function store(Post $post) { $this->validate(request(), ['body' => 'required|min:2']); // 通过post的comments关联创建评论,自动设置post_id $post->comments()->create([ 'body' => request('body'), 'user_id' => auth()->id() ]); return back(); }
如果你想继续使用publishComment方法,可以修改User模型的方法,让它同时关联文章:
// User.php public function publishComment(Comment $comment, Post $post) { $comment->post()->associate($post); // 关联目标文章 $this->comments()->save($comment); // 保存评论,自动设置user_id }
然后在store方法里调用:
public function store(Post $post) { $this->validate(request(), ['body' => 'required|min:2']); $comment = new Comment(['body' => request('body')]); auth()->user()->publishComment($comment, $post); return back(); }
第三步:模板添加容错处理
为了避免因用户不存在导致的报错,在Blade模板中使用可选链操作符(PHP 8.0+支持):
{{ $comment->user?->name }}
如果你的PHP版本低于8.0,可以使用optional辅助函数:
{{ optional($comment->user)->name }}
这样就能彻底解决你遇到的报错问题啦!
内容的提问来源于stack exchange,提问作者chazecka
相关产品推荐
相关产品推荐

