1

I'm working on a questionnaire project and I ran into an error saying:

Undefined index: exams

This happened when I was trying to store responses to my database.

Here is my controller code:

    public function store(Math $math)
    {
        $data = request()->validate([
            'responses.*.answer_id' => 'required',
            'responses.*.question_id' => 'required'
        ]);

        $exam = $math->exams()->create($data['exams']);
        $exam->examanswers()->createMany($data['examanswers']);

        return 'Thank You';
    }

Here is my exam model:

{
    use HasFactory;
    protected $fillable = ['exam'];

    public function math()
    {
        return $this->belongsTo(Math::class);
    }

    public function examanswers()
    {
        return $this->hasMany(ExamAnswer::class);
    }
}

question model:

{
    use HasFactory;
    protected $fillable = ['question'];

    public function math()
    {
        return $this->belongsTo(Math::class);
    }

    public function answers()
    {
        return $this->hasMany(Answer::class);
    }
}

Math model:

{
    use HasFactory;
    protected $fillable = [
        'user_id', 'title', 'purpose', 'exam'
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function questions()
    {
        return $this->hasMany(Question::class);
    }

    public function exams()
    {
        return $this->hasMany(Exam::class);
    }
}

Please help me look into it.

Iam-kelvin
  • 25
  • 3

1 Answers1

1

request()->validate(RULES) will return an array with all the existing rules' indexes. It will not return all data present, just what it is in the rules and present.

Read how $request->validate() works.

For example:

If you send home = 'Address', name = 'John' and email = 123, but your rules are:

$data = $request->validate([
    'home' => 'required',
    'name' => 'required',
]);

Then, if you want to use $data you would have (dd($data)):

  • $data['home']: Address
  • $data['name']: John

But email = 123 would not be present in $data.

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43