【问题标题】:Laravel 8: Undefined indexLaravel 8:未定义的索引
【发布时间】:2021-10-06 10:23:39
【问题描述】:

我正在做一个问卷调查项目,我遇到了一个错误:

未定义索引:考试

这发生在我尝试将响应存储到我的数据库时。

这是我的控制器代码:

    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';
    }

这是我的考试模型:

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

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

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

问题模型:

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

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

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

数学模型:

{
    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);
    }
}

请帮我看看。

【问题讨论】:

  • 为什么$data['exams']应该存在?
  • 看看你的验证规则..我没有看到“考试”。
  • @Maksim 我实际上是在跟随我的导师,这是课程后的项目,没有考试验证,但现在尝试消除了错误
  • @AlbertoSinigaglia :它存在是因为我试图保存用户的回复
  • 为什么不请教老师?

标签: laravel laravel-8 undefined-index


【解决方案1】:

request()->validate(RULES) 将返回一个包含所有现有rules' indexes 的数组。它不会返回所有存在的数据,只返回规则中的数据和存在的数据。

了解$request->validate() 的工作原理。

例如:

如果您发送home = 'Address'name = 'John'email = 123,但您的规则是:

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

那么,如果您想使用$data,您将拥有 (dd($data)):

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

但是email = 123 不会出现在$data 中。

【讨论】:

    猜你喜欢
    • 2021-01-07
    • 1970-01-01
    • 2018-08-02
    • 2012-08-24
    • 2015-03-23
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 2020-02-10
    相关资源
    最近更新 更多