简体   繁体   中英

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

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,
        ]);
    }
}

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

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM