Counting total posts by a user in the blade view

邮差的信 提交于 2019-12-02 04:51:18

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>

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!