1

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);
    }
}
Finchy70
  • 441
  • 9
  • 25

2 Answers2

4

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>
Amin Fazlali
  • 1,209
  • 1
  • 9
  • 17
0

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();
Mahdi Younesi
  • 6,889
  • 2
  • 20
  • 51