Counting total posts by a user in the blade view

前端 未结 2 498
甜味超标
甜味超标 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();
    

提交回复
热议问题