Wait, you created another post with the same problem that was already solved for you? https://laracasts.com/discuss/channels/laravel/how-to-count-the-record-from-another-table-display-it-in-for-loop
Aug 7, 2023
39
Level 1
How to count a record from another table display it in for loop
I need to count likecom table and count by comment_id row
How to equal the comment_id there is relationship with topic and user.
$comments = Comment::where('topic_id', $topic->id)->with('user', function ($q) {
$q->withCount(['comment','like','likecom' => function ($lq) {
$lq->where('comment_id', ???);
}
,'topic' => function ($tq) {
$tq->where('status', 1);
}]);
})
->orderBy('id', 'ASC')->paginate(getPaginate(20));
Blade is like this
<a href="{{route('user.topic.like.comment',$comment->id)}}" class="btn btn-md btn--gradient py-0 m-1">
@if($comment->id == $topic->likecom->comment_id)
<i class="white-font size-btn fa fa-thumbs-up"></i> @lang('You Liked!') ({{ $comment->user->likecom_count }})
@else
<i class="white-font size-btn fa fa-thumbs-o-up"></i> @lang('Like') ({{ $comment->user->likecom_count }})
@endif
</a>
Level 122
@johnpapi create a new relationship in the Comment model
public function likedBy()
{
return $this->belongsToMany(User::class, 'like_comments);
}
query
$comments = Comment::query()
->where('topic_id', $topic->id)
->with('user','likedBy:id')
->orderBy('id', 'ASC')
->paginate(getPaginate(20));
view, to display the count of likes
{{ $comment->likedBy->count() }}
view, to display the buttons
<a href="{{route('user.topic.like.comment',$comment->id)}}" class="btn btn-md btn--gradient py-0 m-1">
@if($comment->likedBy->contains('id',Auth::id()))
<i class="white-font size-btn fa fa-thumbs-up"></i> @lang('You Liked!') ({{ $comment->user->likecom_count }})
@else
<i class="white-font size-btn fa fa-thumbs-o-up"></i> @lang('Like') ({{ $comment->user->likecom_count }})
@endif
</a>
1 like
Please or to participate in this conversation.