[英]Array to string conversion (laravel 7)
I want to make a quiz app in Laravel and I've got some error: array to string conversion
我想在 Laravel 中制作一个测验应用程序,但出现了一些错误:
array to string conversion
This is my controller:这是我的 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');
}
This is my question model:这是我的问题 model:
public function storeQuestion($data)
{
return Pertanyaan::create($data);
}
This is my answer model:这是我的答案 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,
]);
}
}
You have to use like this你必须像这样使用
return $this->validate($request, [
'quiz_id' => 'required',
'question' => 'required',
'options' => 'required|array',
'correct_answer' => 'required',
]);
Then your error remove automatically array to string conversion
然后你的错误自动删除
array to string conversion
this error i got when i use guarded in model, so i change it to fillable and it work properly.当我在 model 中使用受保护时出现此错误,因此我将其更改为可填充并且它可以正常工作。 sorry if im not capturing all of my model.
抱歉,如果我没有捕获我所有的 model。
after read the documentation about special variable eloquent, i lil understand.在阅读了有关特殊变量 eloquent 的文档后,我明白了。 here the link i read but in indonesian leanguage.
这是我阅读的链接,但使用的是印度尼西亚语。 and sorry for my bad english sir.
对不起我糟糕的英语先生。 im new here
我是新来的
https://id-laravel.com/post/mengenal-eloquent-variable-spesial/ https://id-laravel.com/post/mengenal-eloquent-variable-spesial/
When I had this error, it was caused by an error in my Model.当我遇到此错误时,它是由我的 Model 中的错误引起的。 I had the table name formatted as an array, like
protected $table = ['log'];
我将表名格式化为数组,例如
protected $table = ['log'];
. . Correcting this to
protected $table = 'log';
将其更正为
protected $table = 'log';
fixed the problem.解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.