dongzhong2018 2019-02-21 06:26
浏览 43
已采纳

“此集合实例上不存在Property [body]

I am making a blog and it has some weird issue. I used OneToMany joins between comments and posts model(one post can have many comments) on post model:

public function comments(){
    return $this->hasMany('App\Comment');
}

and on comment model:

public function Posts(){
    return $this->belongsTo('App\Posts');
}

now the problem i encountered is in show.blade.php which receives data from controller from show() method of controller and returns some data in view about posts.

public function show($id)
{
   $post = Posts::find($id);
   return view('posts.show')->with('post', $post);
}

and from blade template, I am showing comments related with that post acc to postid

<div class="card-body">
     <h5 class="card-title"><strong>test comment:</strong></h5>
     <p class="card-text">{{$post->comments->body}}</p>
</div>

when I display the comment in blade removing body I get this: data from comments table

i tried $post->comments->body but i get error what is wrong with this, the suggestion would be appreciated

  • 写回答

1条回答 默认 最新

  • doudou201701 2019-02-21 06:29
    关注

    comments is a collection instance you need to loop through

    @foreach($post->comments as $comment)
     <p class="card-text">{{$comment->body}}</p>
    @endforeach
    

    Or alternatively with single comment {{$post->comments[key]->body}} Replace key with index like

    {{$post->comments[0]->body}}

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题