Search code examples
foreachviewlaravel-8laravel-blade

loop through array using foreach laravel blade template


I want to count the number of comments posted on each video. i have been constantly failed to get the desired result.

Here is the data comming from my DB

["data",{"res":[{"videoId":"10"},{"videoId":"40"}],"comments":[{"videoId":"10","total":1},{"videoId":"40","total":2}]}]

result should be in the desired format given below:

videoId ----- total comments
10             1
40             2

Here is the screen shot attached

enter image description here


Solution

  • one video has so many comments that is being posted by user Here is my laravel Relationship that is one to many

    public function GetVideoComments(){
    
            return $this->hasMany('App\Comment', 'videoId', 'videoId');
    
        }
    

    Here is the count the number of comments posted on each video.

    $posts = VideoComment::withCount('GetVideoComments')->get();
    $posts->sum('comments_count');
    

    the above give be the number of total comments posted on each video.