0

I have a quiz. The quiz has 10 questions. First time I saved 7 questions of the quiz using the below code.In the second case I wanted to save the quiz questions again. But in this case the data is being duplicated. I want the question that have been saved once not to be saved in the second time.

     foreach($request->input('questions', []) as $key => $question){
            QuizSessionAnswer::create([
                'session_id'=> $sessionId,
                'question_id'=> $question,
                'selected_choice_id'=> $request->input('choice.'.$question),
                'created_by_id'=> auth()->user()->id,
            ]);
        }

How can I solve the problem?

Habibur Rahman
  • 67
  • 2
  • 12
  • Well, you're using `::create()`, which is going to create a new record every time... You need to add some logic to check for a record with those IDs (all or a subset), and create or update accordingly. – Tim Lewis Jan 22 '21 at 18:21
  • what combinations of the columns make a question unique in your case? – Ahmad Karimi Jan 23 '21 at 18:52

1 Answers1

1

You can one of two

  1. try updateOrCreate method, you can review Laravel Reference here.
  2. you need to identify in your "view form" if you will create a QUIZ questions (send to a quiz.create route) or edit your questions (send to a quiz.edit route)
BQRoster
  • 21
  • 1