Counting total posts by a user in the blade view

前端 未结 2 455
甜味超标
甜味超标 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 16:57

    Yes it is bad.

    You could use relationships if have the user_id field in posts table

    class User extends Model
    {
      public function posts()
      {
         return $this->hasMany('App\Post');
      }
    }
    

    In controller

    return view('sth')->with(['posts'=>$user->posts]);
    

    Then in view

    $posts->count();
    

    Or just getting counts if you don't need posts

    $postCount = $user->posts()->count();
    
    0 讨论(0)
  • 2021-01-25 17:02

    Simple solution:

    <p class="joined-text">Posts: {{ App\Posts::where('user_id', $post->user_id)->count() }}</p>
    

    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:

    <p class="joined-text">Posts: {{ $post->user->posts_count }}</p>
    
    0 讨论(0)
提交回复
热议问题