Count the votes of an article

Published 1 month ago by SmokeTM

Hey guys,

wanna count the votes of an article according to an authenticated user. So this means I wanna count all rows where article.id = article_votes.article.id and where the article belongst to the authenticated user.

What I have so far

$articles = Article::WithCount('votes')->with('votes')->where('user_id', auth()->user()->id)->get();

Now $articles has two ids for which I wanna count the rows in my article_votes table, but how can I do that?

Best regards

Best Answer (As Selected By SmokeTM)
Snapey

My solution gave you a collection of articles, each with a 'votes_count' attribute. You can sum those directly

$totalVotes = $articles->sum('votes_count');
InspiredPrynce

If you are using eloquent relationships, you should be doing something like this...


$article = auth()->user()->articles()->find(1); 
//where 1 is thr article Id

$article->votes()->count();

SmokeTM

Thanks for your answer but how do I get all articles of an authenticated user.

All does not exist?

$articles = auth()->user()->articles()->all();
dd($articles);

$count = $articles->votes()->count();
dd($count);
Snapey
Snapey
1 month ago (1,040,195 XP)

I assume you want the votes per article not just a total?

$articles = auth()->user()->articles()->withCount('votes')->get();
SmokeTM

Did it now as follows and it works but I dont know if this is best practice. Maybe there is a more efficient way to do this.

$articles = auth()->user()->articles()->get();
 //where 1 is thr article Id
 $count = 0;
 foreach ($articles as $article) {
     $count += $article->votes()->count();
 }
Snapey
Snapey
1 month ago (1,040,195 XP)

did my suggestion not work?

Snapey
Snapey
1 month ago (1,040,195 XP)

do you want likes per article or the total?

SmokeTM

The total sum of likes for all articles an auth user has. Your suggestion gave me an collection of articles.

Snapey
Snapey
1 month ago (1,040,195 XP)

My solution gave you a collection of articles, each with a 'votes_count' attribute. You can sum those directly

$totalVotes = $articles->sum('votes_count');
SmokeTM

Thanks a lot works perfectly!

Please sign in or create an account to participate in this conversation.