试图在评论Laravel系统中获取非对象的属性“名称”

问题描述 投票:0回答:2

我试图让作者的用户名在页面上显示评论时显示他们写的评论附近。我有一个错误“试图获取非对象的属性'名称”


控制器:

public function index(Site $site)
    {

        $comments=Comments::where('siteId', $site->id)->get();
        return view('admin.comments.show', compact('comments'));
    }

视图:

    @foreach($comments as $comment)

{{$comment->user->name}}

    @endforeach

用户模型:

public function comments()
  {
      return $this->hasMany(Comments::class);
  }

评论模型:

public function comments()
    {
        return $this->belongsTo(User::class);
    }

我想用关系。谢谢你的帮助! :)

php laravel
2个回答
1
投票

Comment模型中的关系更改为:

public function user()
    {
        return $this->belongsTo(User::class);
    }

这应该工作。


1
投票

在用户模型中:

public function comments()
  {
      return $this->hasMany(Comment::class); // change Comments to Comment here
  }

在评论模型中:

public function user()
    {
        return $this->belongsTo(User::class);
    }
© www.soinside.com 2019 - 2024. All rights reserved.