'Check if auth user has voted and then take count of polls?

I encountered an issue that blocks my way forward.

I have tried getting count of polls as of now as shown below:

 public function user_dashboard(){

        $activepolls = DB::table('larapoll_polls')
                ->selectRaw('count(*) As total')
                ->join('larapoll_options', 'larapoll_polls.id', '=', 'larapoll_options.poll_id')
                ->join('larapoll_votes', 'larapoll_votes.option_id', '=', 'larapoll_options.id')
                ->where('larapoll_votes.user_id', auth()->user()->id)
                ->count();

        return view('user_dashboard',compact('activepolls'));
    }

As of Now I am thinking that this below function would have help me but i am not sure.

public function hasVoted($poll_id)
    {
        $poll = Poll::findOrFail($poll_id);

        if ($poll->canGuestVote()) {
            $result = DB::table('larapoll_polls')
                ->selectRaw('count(*) As total')
                ->join('larapoll_options', 'larapoll_polls.id', '=', 'larapoll_options.poll_id')
                ->join('larapoll_votes', 'larapoll_votes.option_id', '=', 'larapoll_options.id')
                ->where('larapoll_votes.user_id', auth()->user()->id)
                ->where('larapoll_options.poll_id', $poll_id)->count();
            return $result !== 0;
        }

        return $this->options()->where('poll_id', $poll->id)->count() !== 0;
    }

Simply i had made a poll box in my website and i want to show the count of polls in right corner of that box.

  1. i need the count of poll in which user has not voted.
  2. if user votes on poll it should remove from count as well.

If anyone can help , the response would much appreciated..

Thanks..



Solution 1:[1]

I have Solved The issue by following code...

$activepolls = DB::table('larapoll_polls')
                ->selectRaw('count(*) As total')
                ->join('larapoll_options', 'larapoll_polls.id', '=', 'larapoll_options.poll_id')
                ->join('larapoll_votes', 'larapoll_votes.option_id', '=', 'larapoll_options.id')
                ->where('larapoll_votes.user_id', auth()->user()->id)
                ->count();

$polls = Poll::count();

$unvotedpolls = ($polls - $activepolls);

in ($unvotedpolls) i got the count of polls in which auth user has not voted...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jayrajsinh solanki