Laravel hasMany relation count number of likes and comments on post

前端 未结 4 1880
刺人心
刺人心 2020-12-14 04:35

The code:

$posts = Jumpsite::find($jid)
            ->posts()
            ->with(\'comments\')
            ->with(\'likes\')
            ->with(\         


        
4条回答
  •  独厮守ぢ
    2020-12-14 05:27

    Count comments for all blog posts in laravel

    Step 1: Place this code inside your ‘Post’ model.

    // Get the comments for the blog post.
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
    

    Step 2: Place this code inside your ‘PostController’ controller.

     $posts= Post::all();
     return view('home')->with('posts', $posts);
    

    Step 3: Then count comments for all posts using the below code.

    @foreach($posts as $row)
     {{$row->comments->count()}}
    @endforeach
    

    See details here: http://www.pranms.com/count-comments-for-all-blog-posts-in-laravel/

提交回复
热议问题