I have sent a collection of all posts in my blog to my index view and then used the following code to count the total posts made by each user.
Simple solution:
Posts: {{ App\Posts::where('user_id', $post->user_id)->count() }}
Updated
Complete and better solution:
Post.php
:
public function user(){
return $this->belongsTo(App\User::class);
}
User.php
:
public function posts(){
return $this->hasMany(App\Post::class);
}
public function getPostsCountAttribute(){
return $this->posts()->count();
}
blade:
Posts: {{ $post->user->posts_count }}