Laravel - Error encoding model [App\QuestionOption] with ID [] to JSON: Recursion detected

Viewed 6751

I am trying to save data into QuestionOption table and facing issue of recursion detected. I have been searching everywhere but could find any answer to this issue. Following is the where i am trying to save data into DB.

$question = new Question();
    $question->type = $request->type;
    $question->optional = $request->optional;
    $question->question = $request->question;
    $question->status = $request->status;
    $question->save();     ////// WORKS PERFECTLY TILL THIS LINE
    if ($request->type == 'choice') {
        foreach ($request->options as $key => $option) {
            $option = new QuestionOption();  ////////HERE I AM FACING THAT ERROR
            $option->question_id = $question->id;
            $option->option = $option;
            $option->status = 'active';
            $option->save();
        }
    }

Following is the model I am using for QuestionOption, i could not find anything wrong with this.

class QuestionOption extends Model
{

    protected $dates = [
        'created_at',
        'updated_at',
    ];

   protected $fillable = [
        'question_id',
        'option',
        'status',
        'created_at',
        'updated_at',
   ];
}

Please guide me through this. Thanks!

1 Answers

this is a silly mistake of you. you are using $option variable for foreach loop and as an instance of QuestionOption class. and here comes the error when you are assigning $option->option = $option; as because $option is now the instance of QuestionOption class not the variable from foreach loop. change a variable name. like in foreach loop

foreach ($request->options as $key => $value) {
    $option = new QuestionOption();
    $option->question_id = $question->id;
    $option->option = $value;
    $option->status = 'active';
    $option->save();
}
Related