首页 > 解决方案 > 如何在 Laravel 的帖子下发表评论?

问题描述

我有一种方法,可以将评论添加到数据库中。对于每个帖子,自己的评论。我的带有表单的刀片页面有一个隐藏的输入,来自女巫,我接受了 id post

<input type="hidden" value="{{ $post->post_id }}" name="post_id">

我的方法

public function store(Request $request)
{
    $comment = new Music_comment();
    $comment->comment = $request->comment;
    $comment->author_id = \Auth::user()->id;
    $comment->post_id = (int)$request->input('post_id');

    $comment->save();

    return redirect()->back()->with('success', 'Комментарий добавлен');    
}

但是我无法获取帖子下的评论,必须在每个帖子下显示与帖子ID相对应的定义评论。我的视图作曲家方法:

View::composer('*', function($music) {
        $music->with(['post_comment' => Music_comment::orderBy('created_at', 'desc')->limit(4)->get()]);
    });

标签: laravel

解决方案


如果您应该在Music_commentModel 和Post它上显示模型关系,那就太好了。假设您已经正确定义了关系,您可以这样做。

View::composer('*', function($music) {
        $music->with(['post.comment' => function($query){
                $query->orderBy('created_at', 'desc')->limit(4);
        };
    });

希望这可以帮助。

附言

如果你想检索经过身份验证的用户的 id 你可以这样做Auth::id()


推荐阅读