public function votePoll($poll_id, $id, $type) { $user_id = \Auth::user()->id; $isVote = $type == 1; $poll = PollsDemand::with('details')->findOrFail($poll_id); $pollDeamndVotes = PollDemandsVote::findOrNew(1)->where(array('user_id' => $user_id, 'polls_demand_id' => $poll_id)); foreach ($pollDeamndVotes->get() as $pollDeamndVote) { $detail = $poll->details->find($pollDeamndVote->polls_demands_details_id); $detail->total_votes = $detail->total_votes - 1; $detail->save(); } $pollDeamndVotes->delete(); if ($isVote) { $pollDemandsVotes = new PollDemandsVote(); $pollDemandsVotes->user_id = $user_id; $pollDemandsVotes->polls_demand_id = $poll_id; $pollDemandsVotes->polls_demands_details_id = $id; $pollDemandsVotes->save(); $detail = $poll->details->find($id); $detail->total_votes = $detail->total_votes + 1; $detail->save(); } $total_count = 0; foreach ($poll->details as $detail) { $total_count += $detail->total_votes; } $poll->total_votes = $total_count; $poll->save(); return response()->json(['success' => true]); }
public function isVoted() { $vote = \App\Models\PollDemandsVote::findOrNew(1)->where(array('user_id' => \Auth::user()->id, 'polls_demand_id' => $this->id))->get(); return $vote->count() > 0; }