Qasim Ali
Qasim Ali

Reputation: 597

saving array of array into database laravel

I have gone through an earlier post Storing Array of Arrays Let me firstly show what I have tried

Code:

public function createQuestions(Request $request)
{
  $elements = 0;
  while($elements < count($data["question"])) {
     $dataArray[] = array(
       question'          => $data['question'][$elements],
       'answer'            => $data['answer'][$elements],
       'questionnaire_id'  => $data['questionnaire_id'][$elements],
       'type'              => $data['type'][$elements],
       'flag'              => $data['flag'][$elements],
       'choice'              => $data['choice'][$elements],
       'created_at'    => Carbon\Carbon::now(), // only if your table has this column
       'updated_at'    => Carbon\Carbon::now(), // only if your table has this column
        );
$elements++;

}
Question::create($dataArray);

    return back()->with('message', 'Questionnaire is being created successfully'); 
}

The problems I am facing are different. Whenever I run the code. It throws an error

Undefined offset: 1

secondly it throws an error

General error: 1364 Field 'answer' doesn't have a default value. This error is being thrown for every database column.

I have declared these in fillable. Hence there should not be any issue.

protected $fillable = [
    'question', 'idea_id', 'answer', 'type', 'choice', 'flag',
];

I have changed my app name to Questionnaire May be this is the issue?

Upvotes: 0

Views: 88

Answers (2)

Mruf
Mruf

Reputation: 808

It seems there is an answer missing.

Try something like:

...
'answer'            => (array_key_exists($elements,$data['answer']))?$data['answer'][$elements]:"", // default value
...

Honestly the best solution would be to change your migration:

$table->text()->default("");

But the problem here, seems to be a missing parameter from the post request maybe.

Upvotes: 1

Jan Willem
Jan Willem

Reputation: 1320

You can just use Eloquent's method insert:

Question::insert($dataArray);

Note: this will not update or set timestamps. But you added these timestamps in your $dataArray manually, so you already fixed this yourself.

Upvotes: 0

Related Questions