【发布时间】:2018-10-20 16:14:12
【问题描述】:
我正在学习 Laravel,但有一件事我无法解决。
我有什么:
用户、帖子、评论和相应模型表
用户.php:
public function comments() { return $this->hasMany(Comment::class); }
public function publishComment(Comment $comment)
{
$this->comments()->save($comment);
}
Post.php:
public function comments() { return $this->hasMany(Comment::class); }
comment.php:
public function post() { return $this->belongsTo(Post::class); }
public function user() { return $this->belongsTo(User::class); }
我想要什么?
由于我有博客,一个登录用户可以创建许多帖子(这可行)。 但是同一个登录用户可以为一篇文章创建许多 cmets。 (用户有很多 cmets,post 有很多 cmets)。
表格:
用户:|编号 |姓名 |电子邮件 |密码
评论:|编号 |用户 ID | post_id |身体
帖子:|编号 |用户 ID |标题 |身体
我尝试了什么? 我创建了控制器
评论控制器:
class CommentsController extends Controller
{
public function store(Post $post)
{
$this->validate(request(), ['body' => 'required|min:2']);
auth()->user()->publishComment(
new Comment(request('body'));
);
return back();
}
在我的刀片文件中,我只想要 $comment->user->name(获取评论所属的用户名)
我得到的错误: 试图获取非对象的属性
<?php echo e($comment->user->name); ?>
任何帮助将不胜感激。
【问题讨论】:
-
您是否将 $comment 变量传递给刀片视图?
-
@foreach($post->cmets as $comment) 是的,抱歉没有提到这个
标签: laravel