LaravelでhasManyなテーブルの数をカウント

Joinでまとめて取得

<?php
$users = User::join('posts','posts.user_id','=','users.id')
    ->groupBy('users.id')
    ->get(['users.id','users.name',DB::raw('count(posts.id) as posts_cnt')]);


foreach($users as $user){
    echo $user->name . '('.$user->posts_cnt.')<br>';
}

モデルのhasManyの定義を利用して取得

//Model
<?php
class User extends Model{
    public function posts(){
        return $this->hasMany("App\Post", 'user_id','id');
    }
    .   
    .   
}
//Controller and View
$users = User::get();
foreach($users as $user){
    echo $user->name . '('.$user->posts()->count().')<br>';
}