Counting total posts by a user in the blade view

≡放荡痞女 提交于 2019-12-20 04:43:20

问题


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.

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

Is this bad practice to do this from within the blade view? If it is how would I achieve this?

Models

class Posts extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function comments()
    {
        return $this->hasMany(Comments::class, 'post_id');
    }
}





class User extends Authenticatable
{

    public function posts()
    {
        return $this->hasMany('\App\Posts::class');
    }

    public function comments()
    {
        return $this->hasMany(Comments::class);
    }
}

回答1:


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>



回答2:


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();


来源:https://stackoverflow.com/questions/48721466/counting-total-posts-by-a-user-in-the-blade-view

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