[英]Array to string conversion (laravel 7)
我想在 Laravel 中制作一个测验应用程序,但出现了一些错误: array to string conversion
这是我的 controller:
public function validateForm1($request)
{
return $this->validate($request, [
'quiz_id' => 'required',
'question' => 'required',
'options' => 'required|array',
'options.*' => 'required|string',
'correct_answer' => 'required',
]);
}
public function buat(Request $request)
{
$data = $this->validateForm1($request);
$question = (new Pertanyaan)->storeQuestion($data);
$Answer = (new Jawaban)->storeAnswer($data,$question);
return redirect()->back()->with('message','Pertanyaan berhasil disimpan');
}
这是我的问题 model:
public function storeQuestion($data)
{
return Pertanyaan::create($data);
}
这是我的答案 model:
public function storeAnswer($data, $question)
{
foreach ($data['options'] as $key => $option) {
$is_correct = false;
if ($key == $data['correct_answer']) {
$is_correct = true;
}
$answer = Jawaban::create([
'question_id' => $question->id,
'answer' => $option,
'is_correct' => $is_correct,
]);
}
}
你必须像这样使用
return $this->validate($request, [
'quiz_id' => 'required',
'question' => 'required',
'options' => 'required|array',
'correct_answer' => 'required',
]);
然后你的错误自动删除array to string conversion
当我在 model 中使用受保护时出现此错误,因此我将其更改为可填充并且它可以正常工作。 抱歉,如果我没有捕获我所有的 model。
在阅读了有关特殊变量 eloquent 的文档后,我明白了。 这是我阅读的链接,但使用的是印度尼西亚语。 对不起我糟糕的英语先生。 我是新来的
https://id-laravel.com/post/mengenal-eloquent-variable-spesial/
当我遇到此错误时,它是由我的 Model 中的错误引起的。 我将表名格式化为数组,例如protected $table = ['log'];
. 将其更正为protected $table = 'log';
解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.