Counting total posts by a user in the blade view

前端 未结 2 454
甜味超标
甜味超标 2021-01-25 16:25

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.

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-25 17:02

    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 }}

提交回复
热议问题