I am trying to build an API to store and retrieve MCQ exam papers. I am using laravel resource class to send handle Json data. I need to insert 40 records into MySQL databas
This code works for me. It inserted all 40 records with no problems.
$array = $request->all();
foreach($array["data"] as $row)
{
Exam_Paper::create(['paper_id' => $row["paper_id"],
'question_no' => $row["question_no"],
'question' => $row["question"],
'answer1' => $row["answer1"],
'answer2' => $row["answer2"],
'answer3' => $row["answer3"],
'answer4' => $row["answer4"],
'answerC' => $row["answerC"],
'knowarea' => $row["knowarea"],
]);
}
Try code below
$jsonarray =json_decode(json_encode($b),TRUE); // $b=your json array
foreach ($jsonarray as $key => $value)
{
foreach ($value as $a => $b)
{
$qry=DB::insert('insert into your_table(colomn_name1,colomn_name2)values(?,?)',[$b['indexname1'],$b['indexname2']]); //index name will be paper_id,question_no etc
}
}
your code will look like this
public function bulkdata(Request $request)
{
$b=$request->input('data');
$jsonarray =json_decode(json_encode($b),TRUE);
foreach ($jsonarray as $key => $value)
{
foreach ($value as $a => $b)
{
$qry=DB::insert('insert into yourtable(paper_id,question_no,question,answer1,answer2,answer3,answer4,answerC,knowarea)values(?,?,?,?,?,?,?,?,?)',[$b['paper_id'],$b['question_no'],$b['question'],$b['answer1'],$b['answer2'],$b['answer3'],$b['answer4'],$b['answerC']$b['knowarea']);
}
}
}
Based on your sample data, you can json_decode
the data and then use a single Model::insert()
:
{
"data":[
{
"paper_id":"5",
"question_no":"2",
"question":"test insert code",
"answer1":"answer1",
"answer2":"answer2 ",
"answer3":"answer3 ",
"answer4":"Answer4 ",
"answerC":"Correct Answer",
"knowarea":"who knows!"
},
...
]
}
// Controller.php
public function store($json)
{
$data = json_decode($json, true);
Paper::insert($data);
}
That will create arrays from your json and then insert all the records at once.
You can use: Eloquent::insert()
Like example below.
$data = array(
array('name'=>'Coder 1', 'rep'=>'4096'),
array('name'=>'Coder 2', 'rep'=>'2048'),
//...
);
Coder::insert($data);
insert select query with update models array field
$newModelsArray=ModelTable::where(....)->get();
foreach ($newModelsArray as $objectItr) {
$newObjectItr = $objectItr->replicate();
$newObjectItr->field=newValue;
$newObjectItr->save();
}
and there you'll update and save in to the table (clone it back to the database) ->replicate() will clone the modelObject and the ->save() will add it to the database inside the loop !
Thanks Ali