Reputation: 153
I'm trying to retrieve the number of likes
and dislikes
a post have.
I've the following table in database, in which I've like
column which decides like or dislike. if it is 1
it means like
if it is zero
it means dislike
.
Problem :
I'm trying to count
the number of like(s)
a post has and then show it for each post, I'm trying to achieve this using ternary operator but I'm getting 1
like and 1
dislike for every post which is wrong according to the above table data.
Is there anything I'm doing wrong, because I think the code should work .
Because for post_id
1
the number of likes should be 2
according to the table , but I get 1
like and 1
dislike for each post.
Code
This is the code I'm trying to get the number of likes
and dislikes
@if(count( $post->likes()->where('$post->like'==1) )>=1 )
<small>{{ count($post->likes()->where('$post->like' ==1))>=1?count($post->likes()->where($post->like ==1)). ' Likes':count($post->likes()->where($post->like ==1)).'Dislike' }}</small>
@else
<small>// similary do this for dislikes when like column in the above table is 0</small>
@endif
</small>
Upvotes: 1
Views: 693
Reputation: 1652
You can use the count and withCount method from eloquent to make this easier for you
You can count the likes and dislikes in your controller like this:
$posts = App\Post::withCount([
'likes' => function ($query) {
$query->where('like', 1);
},
'likes as dislikes_count' => function ($query) {
$query->where('like', 0);
}
])->get();
Then you can those counts this in your blade like
Likes count: {{ $post->likes_count }}
Dislikes count: {{ $post->dislikes_count }}
Upvotes: 2