The code:
$posts = Jumpsite::find($jid)
->posts()
->with(\'comments\')
->with(\'likes\')
->with(\
In your model place the following accessors:
Count total Likes:
public function getTotalLikesAttribute()
{
return $this->hasMany('Like')->whereUserId($this->author_id)->count();
}
Count total comments:
From your description, i can see, you have retrieving the number of posts as comments
public function getTotalCommentsAttribute()
{
return $this->hasMany('Post')->whereUserId($this->author_id)->count();
}
Now, from your controller:
$post = Jumpsite::find($jid);
// total comments
var_dump( $post->total_comments );
// total Likes
var_dump( $post->total_likes );
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/
You can use that following code for counting relation model result.
$posts = App\Post::withCount('comments')->get(); foreach ($posts as $post) { echo $post->comments_count; }
And also set condition with count like this
$posts = Post::withCount(['votes', 'comments' => function ($query) { $query->where('content', 'like', 'foo%'); }])->get();
Just single change to get results of the count
In relation
public function getTotalLikesAttribute(){
return $this->hasMany('Like')->where('author_id',$this->author_id)->count();
}
In the view
$post->getTotalLikesAttribute()