laravelselectvoting

Laravel : Prevent the user from voting twice


I want to stop a user from voting twice and redirect them to the result page.

Controller

public function view_survey(Survey $survey)
{
    $survey->option_name = unserialize($survey->option_name);
    $answers = \App\Answer::pluck('Answer', 'id')->toArray();

    return view('survey.view', compact('survey', 'answers'));
}

Tables: Table of Answers


Solution

  • A basic way to do this would be:

        public function view_survey(Survey $survey)
        {
                 // get you logged in user
                 $user_id = auth()->user()->id;
                 $survey->option_name = unserialize($survey->option_name);
                 $hasAnswer = \App\Answer::where(['user_id'=>$user_id , 'survey_id' => $survey->id])->exists();//check if user has answer
                 //user has an answer to one of the survey questions. Alternatively, you can also check if all questions are answered, or if a specific question is answered by including question id as well in where
                 if($hasAnswer){
                       return redirect('routetoshowsurvey',$survey_id);
                 }
                 return view('survey.view', compact('survey', 'answers'));
        }