Reputation: 89
I want to make a quiz app in Laravel and I've got some error: array to string conversion
This is my 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:
public function storeQuestion($data)
{
return Pertanyaan::create($data);
}
This is my answer 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,
]);
}
}
Upvotes: 1
Views: 985
Reputation: 15
When I had this error, it was caused by an error in my Model. I had the table name formatted as an array, like protected $table = ['log'];
. Correcting this to protected $table = 'log';
fixed the problem.
Upvotes: 0
Reputation: 5270
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
Upvotes: 1
Reputation: 89
this error i got when i use guarded in model, so i change it to fillable and it work properly. sorry if im not capturing all of my model.
after read the documentation about special variable eloquent, i lil understand. 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/
Upvotes: 0